-- CreateEnum
CREATE TYPE "BillingProvider" AS ENUM ('STRIPE', 'MERCADOPAGO', 'PAYPAL');

-- CreateEnum
CREATE TYPE "BillingStatus" AS ENUM ('TRIAL', 'ACTIVE', 'PAST_DUE', 'CANCELED', 'SUSPENDED');

-- CreateTable
CREATE TABLE "complex_billings" (
    "complex_id" UUID NOT NULL,
    "status" "BillingStatus" NOT NULL DEFAULT 'TRIAL',
    "plan_code" VARCHAR(10) NOT NULL,
    "currency" VARCHAR(3) NOT NULL,
    "provider" "BillingProvider",
    "provider_customer_id" TEXT,
    "provider_subscription_id" TEXT,
    "provider_preapproval_id" TEXT,
    "current_period_start" TIMESTAMP(3),
    "current_period_end" TIMESTAMP(3),
    "trial_ends_at" TIMESTAMP(3),
    "canceled_at" TIMESTAMP(3),
    "suspended_at" TIMESTAMP(3),
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updated_at" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "complex_billings_pkey" PRIMARY KEY ("complex_id")
);

-- CreateTable
CREATE TABLE "billing_events" (
    "id" UUID NOT NULL,
    "complex_id" UUID NOT NULL,
    "event_type" VARCHAR(100) NOT NULL,
    "provider" "BillingProvider" NOT NULL,
    "provider_event_id" TEXT,
    "provider_data" JSONB,
    "previous_status" "BillingStatus",
    "new_status" "BillingStatus",
    "processed_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "billing_events_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "billing_events_provider_event_id_key" ON "billing_events"("provider_event_id");

-- CreateIndex
CREATE INDEX "billing_events_provider_provider_event_id_idx" ON "billing_events"("provider", "provider_event_id");

-- CreateIndex
CREATE INDEX "billing_events_complex_id_idx" ON "billing_events"("complex_id");

-- AddForeignKey
ALTER TABLE "complex_billings" ADD CONSTRAINT "complex_billings_complex_id_fkey" FOREIGN KEY ("complex_id") REFERENCES "complexes"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "billing_events" ADD CONSTRAINT "billing_events_complex_id_fkey" FOREIGN KEY ("complex_id") REFERENCES "complex_billings"("complex_id") ON DELETE RESTRICT ON UPDATE CASCADE;
