-- Migration: Create import_audit_log table
-- Permanent audit trail of all product import submissions sent to the API
-- Run this against your PostgreSQL database

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

  -- Who initiated the import
  user_id INTEGER NOT NULL,
  username VARCHAR(255),

  -- What was submitted
  product_count INTEGER NOT NULL,
  request_payload JSONB NOT NULL,           -- The exact JSON array of products sent to the API
  environment VARCHAR(10) NOT NULL,         -- 'dev' or 'prod'
  target_endpoint VARCHAR(255),             -- The API URL that was called
  use_test_data_source BOOLEAN DEFAULT FALSE,

  -- What came back
  success BOOLEAN NOT NULL,
  response_payload JSONB,                   -- Full API response
  error_message TEXT,                       -- Extracted error message on failure
  created_count INTEGER DEFAULT 0,          -- Number of products successfully created
  errored_count INTEGER DEFAULT 0,          -- Number of products that errored

  -- Metadata
  session_id INTEGER,                       -- Optional link to the import_session used (if any)
  duration_ms INTEGER,                      -- How long the API call took
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Index for looking up logs by user
CREATE INDEX IF NOT EXISTS idx_import_audit_log_user_id
  ON import_audit_log (user_id);

-- Index for filtering by success/failure
CREATE INDEX IF NOT EXISTS idx_import_audit_log_success
  ON import_audit_log (success);

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

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

COMMENT ON TABLE import_audit_log IS 'Permanent audit log of all product import API submissions';
COMMENT ON COLUMN import_audit_log.request_payload IS 'Exact JSON products array sent to the external API';
COMMENT ON COLUMN import_audit_log.response_payload IS 'Full response received from the external API';
COMMENT ON COLUMN import_audit_log.environment IS 'dev or prod - which API endpoint was targeted';
COMMENT ON COLUMN import_audit_log.session_id IS 'Optional reference to import_sessions.id if session was active';
COMMENT ON COLUMN import_audit_log.duration_ms IS 'Round-trip time of the API call in milliseconds';
