-- Migration: Create product_editor_audit_log table
-- Permanent audit trail of all product editor API submissions
-- Run this against your PostgreSQL database

CREATE TABLE IF NOT EXISTS product_editor_audit_log (
  id SERIAL PRIMARY KEY,

  -- Who made the edit
  user_id INTEGER NOT NULL,
  username VARCHAR(255),

  -- Which product
  pid INTEGER NOT NULL,

  -- What was submitted
  action VARCHAR(50) NOT NULL,               -- 'product_edit', 'image_changes', 'taxonomy_set'
  request_payload JSONB NOT NULL,            -- The exact payload sent to the external API
  target_endpoint VARCHAR(255),              -- The API URL that was called

  -- What came back
  success BOOLEAN NOT NULL,
  response_payload JSONB,                    -- Full API response
  error_message TEXT,                        -- Extracted error message on failure

  -- Metadata
  duration_ms INTEGER,                       -- How long the API call took
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Index for looking up edits by product
CREATE INDEX IF NOT EXISTS idx_pe_audit_log_pid
  ON product_editor_audit_log (pid);

-- Index for looking up edits by user
CREATE INDEX IF NOT EXISTS idx_pe_audit_log_user_id
  ON product_editor_audit_log (user_id);

-- Index for time-based queries
CREATE INDEX IF NOT EXISTS idx_pe_audit_log_created_at
  ON product_editor_audit_log (created_at DESC);

-- Composite index for product + time queries
CREATE INDEX IF NOT EXISTS idx_pe_audit_log_pid_created
  ON product_editor_audit_log (pid, created_at DESC);

-- Composite index for user + time queries
CREATE INDEX IF NOT EXISTS idx_pe_audit_log_user_created
  ON product_editor_audit_log (user_id, created_at DESC);

COMMENT ON TABLE product_editor_audit_log IS 'Permanent audit log of all product editor API submissions';
COMMENT ON COLUMN product_editor_audit_log.action IS 'Type of edit: product_edit, image_changes, or taxonomy_set';
COMMENT ON COLUMN product_editor_audit_log.request_payload IS 'Exact payload sent to the external API';
COMMENT ON COLUMN product_editor_audit_log.response_payload IS 'Full response received from the external API';
COMMENT ON COLUMN product_editor_audit_log.duration_ms IS 'Round-trip time of the API call in milliseconds';
