-- Migration 133: Ordre drafts persistence for global /ordre page

CREATE TABLE IF NOT EXISTS ordre_drafts (
    id SERIAL PRIMARY KEY,
    title VARCHAR(120) NOT NULL,
    customer_id INTEGER REFERENCES customers(id) ON DELETE SET NULL,
    lines_json JSONB NOT NULL DEFAULT '[]'::jsonb,
    notes TEXT,
    layout_number INTEGER,
    created_by_user_id INTEGER REFERENCES users(user_id) ON DELETE SET NULL,
    export_status_json JSONB NOT NULL DEFAULT '{}'::jsonb,
    last_exported_at TIMESTAMP,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_ordre_drafts_user ON ordre_drafts(created_by_user_id);
CREATE INDEX IF NOT EXISTS idx_ordre_drafts_updated_at ON ordre_drafts(updated_at DESC);
CREATE INDEX IF NOT EXISTS idx_ordre_drafts_customer ON ordre_drafts(customer_id);

CREATE TRIGGER trigger_ordre_drafts_updated_at
BEFORE UPDATE ON ordre_drafts
FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column();
