CREATE TYPE "AccountSessionStatus" AS ENUM ('ACTIVE', 'REVOKED', 'EXPIRED');

CREATE TABLE "account_sessions" (
  "id" UUID NOT NULL,
  "user_id" UUID NOT NULL,
  "refresh_token_hash" TEXT NOT NULL,
  "status" "AccountSessionStatus" NOT NULL DEFAULT 'ACTIVE',
  "access_token_version" INTEGER NOT NULL DEFAULT 1,
  "expires_at" TIMESTAMP(3) NOT NULL,
  "last_refreshed_at" TIMESTAMP(3),
  "revoked_at" TIMESTAMP(3),
  "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updated_at" TIMESTAMP(3) NOT NULL,
  CONSTRAINT "account_sessions_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX "account_sessions_refresh_token_hash_key"
ON "account_sessions"("refresh_token_hash");

CREATE INDEX "account_sessions_user_id_idx"
ON "account_sessions"("user_id");

CREATE INDEX "account_sessions_status_expires_at_idx"
ON "account_sessions"("status", "expires_at");

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