-- Crédits IA globaux (modèle A) — tables additives uniquement
CREATE TABLE IF NOT EXISTS "AiCreditAccount" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "periodKey" TEXT NOT NULL,
    "subscriptionGranted" INTEGER NOT NULL DEFAULT 0,
    "subscriptionSpent" INTEGER NOT NULL DEFAULT 0,
    "purchasedBalance" INTEGER NOT NULL DEFAULT 0,
    "updatedAt" TIMESTAMP(3) NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

CREATE UNIQUE INDEX IF NOT EXISTS "AiCreditAccount_userId_key" ON "AiCreditAccount"("userId");
CREATE INDEX IF NOT EXISTS "AiCreditAccount_periodKey_idx" ON "AiCreditAccount"("periodKey");

CREATE TABLE IF NOT EXISTS "AiCreditLedger" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "kind" TEXT NOT NULL,
    "amount" INTEGER NOT NULL,
    "feature" TEXT,
    "balanceAfter" INTEGER,
    "metadata" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

CREATE INDEX IF NOT EXISTS "AiCreditLedger_userId_createdAt_idx" ON "AiCreditLedger"("userId", "createdAt");
CREATE INDEX IF NOT EXISTS "AiCreditLedger_userId_feature_createdAt_idx" ON "AiCreditLedger"("userId", "feature", "createdAt");
CREATE INDEX IF NOT EXISTS "AiCreditLedger_userId_kind_createdAt_idx" ON "AiCreditLedger"("userId", "kind", "createdAt");

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint WHERE conname = 'AiCreditAccount_userId_fkey'
  ) THEN
    ALTER TABLE "AiCreditAccount"
      ADD CONSTRAINT "AiCreditAccount_userId_fkey"
      FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
  END IF;
END $$;

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint WHERE conname = 'AiCreditLedger_userId_fkey'
  ) THEN
    ALTER TABLE "AiCreditLedger"
      ADD CONSTRAINT "AiCreditLedger_userId_fkey"
      FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
  END IF;
END $$;
