-- 00005_card_layouts_role_access
-- Adds roleAccess to crm_user_fields + CrmCardLayout tables

-- 1. Add roleAccess column to crm_user_fields
ALTER TABLE "crm_user_fields" ADD COLUMN "roleAccess" JSONB;

-- 2. Migrate showToTrainer → roleAccess
UPDATE "crm_user_fields" SET "roleAccess" =
  CASE WHEN "showToTrainer" = true
    THEN '{"trainer":"readonly","manager":"editable","club_admin":"editable","super_admin":"editable"}'::jsonb
    ELSE '{"trainer":"hidden","manager":"editable","club_admin":"editable","super_admin":"editable"}'::jsonb
  END;

-- 3. CrmCardLayout (admin-default per entity type)
CREATE TABLE "crm_card_layouts" (
    "id" TEXT NOT NULL,
    "clubId" TEXT,
    "entityType" TEXT NOT NULL,
    "fields" JSONB NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- 4. CrmCardLayoutUser (per-user override)
CREATE TABLE "crm_card_layouts_user" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "clubId" TEXT,
    "entityType" TEXT NOT NULL,
    "useDefault" BOOLEAN NOT NULL DEFAULT true,
    "fields" JSONB,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- 5. Unique constraints
CREATE UNIQUE INDEX "crm_card_layouts_clubId_entityType_key" ON "crm_card_layouts"("clubId", "entityType");
CREATE UNIQUE INDEX "crm_card_layouts_user_userId_clubId_entityType_key" ON "crm_card_layouts_user"("userId", "clubId", "entityType");

-- 6. Indexes
CREATE INDEX "crm_card_layouts_clubId_idx" ON "crm_card_layouts"("clubId");
CREATE INDEX "crm_card_layouts_user_userId_idx" ON "crm_card_layouts_user"("userId");
CREATE INDEX "crm_card_layouts_user_clubId_idx" ON "crm_card_layouts_user"("clubId");

-- 7. Foreign keys
ALTER TABLE "crm_card_layouts" ADD CONSTRAINT "crm_card_layouts_clubId_fkey"
    FOREIGN KEY ("clubId") REFERENCES "clubs"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "crm_card_layouts_user" ADD CONSTRAINT "crm_card_layouts_user_userId_fkey"
    FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "crm_card_layouts_user" ADD CONSTRAINT "crm_card_layouts_user_clubId_fkey"
    FOREIGN KEY ("clubId") REFERENCES "clubs"("id") ON DELETE CASCADE ON UPDATE CASCADE;
