CREATE TYPE "SubscriptionStatus" AS ENUM ('TRIAL', 'ACTIVE', 'PAST_DUE', 'CANCELLED', 'EXPIRED');
CREATE TYPE "SubscriptionPlan" AS ENUM ('FREE', 'PRO');
CREATE TYPE "BillingProvider" AS ENUM ('PADDLE');

CREATE TABLE "user_subscriptions" (
  "id" UUID NOT NULL,
  "user_id" UUID NOT NULL,
  "provider" "BillingProvider" NOT NULL,
  "provider_customer_id" TEXT,
  "provider_subscription_id" TEXT,
  "plan" "SubscriptionPlan" NOT NULL,
  "status" "SubscriptionStatus" NOT NULL,
  "current_period_start" TIMESTAMP(3) NOT NULL,
  "current_period_end" TIMESTAMP(3) NOT NULL,
  "cancel_at_period_end" BOOLEAN NOT NULL DEFAULT false,
  "cancelled_at" TIMESTAMP(3),
  "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updated_at" TIMESTAMP(3) NOT NULL,
  CONSTRAINT "user_subscriptions_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX "user_subscriptions_user_id_key"
ON "user_subscriptions"("user_id");

CREATE UNIQUE INDEX "user_subscriptions_provider_customer_id_key"
ON "user_subscriptions"("provider_customer_id");

CREATE UNIQUE INDEX "user_subscriptions_provider_subscription_id_key"
ON "user_subscriptions"("provider_subscription_id");

CREATE TABLE "user_entitlements" (
  "id" UUID NOT NULL,
  "user_id" UUID NOT NULL,
  "entitlement_key" TEXT NOT NULL,
  "granted" BOOLEAN NOT NULL DEFAULT false,
  "source" TEXT NOT NULL,
  "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updated_at" TIMESTAMP(3) NOT NULL,
  CONSTRAINT "user_entitlements_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX "user_entitlements_user_id_entitlement_key_key"
ON "user_entitlements"("user_id", "entitlement_key");

ALTER TABLE "user_subscriptions"
ADD CONSTRAINT "user_subscriptions_user_id_fkey"
FOREIGN KEY ("user_id") REFERENCES "users"("id")
ON DELETE CASCADE
ON UPDATE CASCADE;

ALTER TABLE "user_entitlements"
ADD CONSTRAINT "user_entitlements_user_id_fkey"
FOREIGN KEY ("user_id") REFERENCES "users"("id")
ON DELETE CASCADE
ON UPDATE CASCADE;
