-- Task #257: Gerador de Sender — Chips via GlobalSIM
-- Adiciona global_sim_api_key em services e cria a tabela chip_activations.
--
-- IDEMPOTENTE: usa IF NOT EXISTS e blocos DO $$ para ALTER.

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_name = 'services' AND column_name = 'global_sim_api_key'
  ) THEN
    ALTER TABLE services ADD COLUMN global_sim_api_key TEXT;
  END IF;
END
$$;

CREATE TABLE IF NOT EXISTS chip_activations (
  id               TEXT        NOT NULL DEFAULT gen_random_uuid()::TEXT PRIMARY KEY,
  user_id          TEXT        NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  service_id       TEXT        NOT NULL REFERENCES services(id) ON DELETE CASCADE,
  activation_id    TEXT        NOT NULL,
  phone_number     TEXT,
  sms_code         TEXT,
  internal_name    TEXT,
  status           TEXT        NOT NULL DEFAULT 'pending',
  credit_debited   BOOLEAN     NOT NULL DEFAULT FALSE,
  created_at       TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  activated_at     TIMESTAMPTZ,
  cancelled_at     TIMESTAMPTZ
);
