-- Migration 1003: Ordre draft sync audit + idempotency safeguards

ALTER TABLE ordre_drafts
ADD COLUMN IF NOT EXISTS export_idempotency_key VARCHAR(120);

CREATE UNIQUE INDEX IF NOT EXISTS uq_ordre_drafts_export_idempotency_key
    ON ordre_drafts(export_idempotency_key)
    WHERE export_idempotency_key IS NOT NULL;

CREATE TABLE IF NOT EXISTS ordre_draft_sync_events (
    id SERIAL PRIMARY KEY,
    draft_id INTEGER NOT NULL REFERENCES ordre_drafts(id) ON DELETE CASCADE,
    event_type VARCHAR(50) NOT NULL,
    from_status VARCHAR(20),
    to_status VARCHAR(20),
    event_payload JSONB NOT NULL DEFAULT '{}'::jsonb,
    created_by_user_id INTEGER REFERENCES users(user_id) ON DELETE SET NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_ordre_draft_sync_events_draft_id
    ON ordre_draft_sync_events(draft_id, created_at DESC);

CREATE INDEX IF NOT EXISTS idx_ordre_draft_sync_events_type
    ON ordre_draft_sync_events(event_type, created_at DESC);
