-- CreateTable: roles
CREATE TABLE "roles" (
    "id" TEXT NOT NULL,
    "clubId" TEXT,
    "name" TEXT NOT NULL,
    "slug" TEXT NOT NULL,
    "isBuiltIn" BOOLEAN NOT NULL DEFAULT false,
    "isActive" BOOLEAN NOT NULL DEFAULT true,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable: user_roles (many-to-many)
CREATE TABLE "user_roles" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "roleId" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateIndex
CREATE INDEX "roles_clubId_idx" ON "roles"("clubId");
CREATE UNIQUE INDEX "roles_clubId_slug_key" ON "roles"("clubId", "slug");
CREATE INDEX "user_roles_userId_idx" ON "user_roles"("userId");
CREATE INDEX "user_roles_roleId_idx" ON "user_roles"("roleId");
CREATE UNIQUE INDEX "user_roles_userId_roleId_key" ON "user_roles"("userId", "roleId");

-- AddForeignKey
ALTER TABLE "roles" ADD CONSTRAINT "roles_clubId_fkey" FOREIGN KEY ("clubId") REFERENCES "clubs"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "user_roles" ADD CONSTRAINT "user_roles_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "user_roles" ADD CONSTRAINT "user_roles_roleId_fkey" FOREIGN KEY ("roleId") REFERENCES "roles"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- Seed built-in roles (clubId = NULL = global)
INSERT INTO "roles" ("id", "clubId", "name", "slug", "isBuiltIn", "isActive", "createdAt", "updatedAt") VALUES
  (gen_random_uuid(), NULL, 'Суперадминистратор', 'super_admin', true, true, NOW(), NOW()),
  (gen_random_uuid(), NULL, 'Админ клуба', 'club_admin', true, true, NOW(), NOW()),
  (gen_random_uuid(), NULL, 'Тренер', 'trainer', true, true, NOW(), NOW()),
  (gen_random_uuid(), NULL, 'Фитнес-менеджер', 'manager', true, true, NOW(), NOW()),
  (gen_random_uuid(), NULL, 'Координатор', 'coordinator', true, true, NOW(), NOW()),
  (gen_random_uuid(), NULL, 'Рецепция', 'receptionist', true, true, NOW(), NOW());

-- Migrate existing user.role -> user_roles
INSERT INTO "user_roles" ("id", "userId", "roleId", "createdAt")
  SELECT gen_random_uuid(), u.id, r.id, NOW()
  FROM "users" u
  JOIN "roles" r ON LOWER(u.role::text) = r.slug
  WHERE r."clubId" IS NULL;
