/*
  # Create assinaturas table

  Company subscriptions to plans.
*/

CREATE TABLE IF NOT EXISTS assinaturas (
  id bigserial PRIMARY KEY,
  empresa_id bigint NOT NULL REFERENCES empresas(id) ON DELETE CASCADE,
  plano_id bigint NOT NULL REFERENCES planos(id),
  status text NOT NULL DEFAULT 'trial' CHECK (status IN ('trial','ativo','em_atraso','cancelado','suspenso')),
  periodo text NOT NULL DEFAULT 'mensal' CHECK (periodo IN ('mensal','anual')),
  preco_cobrado bigint NOT NULL DEFAULT 0,
  data_inicio date NOT NULL,
  data_fim date,
  data_prox_cobranca date,
  gateway_assinatura_id text,
  trial_ends_at timestamptz,
  cancelado_em timestamptz,
  motivo_cancelamento text,
  created_at timestamptz DEFAULT now(),
  updated_at timestamptz DEFAULT now()
);

CREATE INDEX idx_assinaturas_empresa_status ON assinaturas(empresa_id, status);

ALTER TABLE assinaturas ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Empresa members can read own assinaturas"
  ON assinaturas FOR SELECT
  TO authenticated
  USING (empresa_id = (SELECT empresa_id FROM usuarios WHERE supabase_uuid = auth.uid()));

CREATE POLICY "Insert assinaturas"
  ON assinaturas FOR INSERT
  TO authenticated
  WITH CHECK (true);

CREATE POLICY "Update assinaturas"
  ON assinaturas FOR UPDATE
  TO authenticated
  USING (true);
