/**
 * Migration: Create email ingestion tables
 * @ai-summary Creates email_ingestion_queue and pending_vehicle_associations tables
 * @ai-context Supports inbound email receipt processing via Resend webhooks
 */

-- email_ingestion_queue: Tracks inbound emails from Resend webhooks
CREATE TABLE IF NOT EXISTS email_ingestion_queue (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  email_id VARCHAR(255) NOT NULL,
  sender_email VARCHAR(255) NOT NULL,
  user_id VARCHAR(255) NOT NULL,
  received_at TIMESTAMP WITH TIME ZONE NOT NULL,
  subject VARCHAR(500),
  status VARCHAR(20) NOT NULL DEFAULT 'pending' CHECK (status IN (
    'pending', 'processing', 'completed', 'failed'
  )),
  processing_result JSONB,
  error_message TEXT,
  retry_count INTEGER NOT NULL DEFAULT 0,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Unique constraint on email_id to prevent duplicate processing
ALTER TABLE email_ingestion_queue
  ADD CONSTRAINT uq_email_ingestion_queue_email_id UNIQUE (email_id);

-- Trigger for updated_at (reuses update_updated_at_column() from vehicles feature)
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_trigger WHERE tgname = 'set_timestamp_email_ingestion_queue'
  ) THEN
    CREATE TRIGGER set_timestamp_email_ingestion_queue
    BEFORE UPDATE ON email_ingestion_queue
    FOR EACH ROW
    EXECUTE FUNCTION update_updated_at_column();
  END IF;
END $$;

-- Indexes
CREATE INDEX IF NOT EXISTS idx_email_ingestion_queue_user_id ON email_ingestion_queue(user_id);
CREATE INDEX IF NOT EXISTS idx_email_ingestion_queue_status ON email_ingestion_queue(status);
CREATE INDEX IF NOT EXISTS idx_email_ingestion_queue_sender ON email_ingestion_queue(sender_email);
CREATE INDEX IF NOT EXISTS idx_email_ingestion_queue_received_at ON email_ingestion_queue(received_at DESC);

-- pending_vehicle_associations: Holds records needing vehicle selection (multi-vehicle users)
CREATE TABLE IF NOT EXISTS pending_vehicle_associations (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  user_id VARCHAR(255) NOT NULL,
  record_type VARCHAR(30) NOT NULL CHECK (record_type IN (
    'fuel_log', 'maintenance_record'
  )),
  extracted_data JSONB NOT NULL,
  document_id UUID REFERENCES documents(id) ON DELETE SET NULL,
  status VARCHAR(20) NOT NULL DEFAULT 'pending' CHECK (status IN (
    'pending', 'resolved', 'expired'
  )),
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  resolved_at TIMESTAMP WITH TIME ZONE
);

-- Trigger for pending_vehicle_associations does not need updated_at (uses resolved_at instead)

-- Indexes
CREATE INDEX IF NOT EXISTS idx_pending_vehicle_assoc_user_id ON pending_vehicle_associations(user_id);
CREATE INDEX IF NOT EXISTS idx_pending_vehicle_assoc_status ON pending_vehicle_associations(status)
  WHERE status = 'pending';
CREATE INDEX IF NOT EXISTS idx_pending_vehicle_assoc_document_id ON pending_vehicle_associations(document_id)
  WHERE document_id IS NOT NULL;
