-- ─────────────────────────────────────────────────────────────────
-- FASE 3: Integração Asaas + PIX e Reservas
-- ─────────────────────────────────────────────────────────────────

-- Tabela Orders (Pedidos/Cobranças Asaas)
CREATE TABLE IF NOT EXISTS orders (
  id             TEXT PRIMARY KEY,  -- Asaas Payment / Charge ID (ex: pay_123456)
  customer_id    TEXT,              -- Asaas Customer ID (ex: cus_00000)
  user_cpf       TEXT NOT NULL,     -- Usado para vincular pagamentos a usuários
  total_amount   NUMERIC(10,2) NOT NULL,
  status         TEXT DEFAULT 'pending' CHECK (status IN ('pending', 'paid', 'canceled', 'expired')),
  payment_method TEXT DEFAULT 'PIX',
  qr_code        TEXT,
  qr_code_url    TEXT,
  pix_copy_paste TEXT,
  created_at     TIMESTAMPTZ DEFAULT NOW(),
  updated_at     TIMESTAMPTZ DEFAULT NOW()
);

-- Ajustes na tabela tickets para suportar reservas
ALTER TABLE tickets ADD COLUMN IF NOT EXISTS status TEXT DEFAULT 'sold' CHECK (status IN ('reserved', 'sold'));
ALTER TABLE tickets ADD COLUMN IF NOT EXISTS reserved_until TIMESTAMPTZ;
ALTER TABLE tickets ADD COLUMN IF NOT EXISTS order_id TEXT REFERENCES orders(id) ON DELETE SET NULL;
ALTER TABLE tickets ADD COLUMN IF NOT EXISTS price_paid NUMERIC(10,2);
