-- ============================================================================
-- Migration: 00002_deal_number_stage_fixes
-- Description:
--   A1: Clean test data duplicates (user_fields, pipelines, lost_reasons)
--   A2: Fix deals with NULL clubId
--   B1-B2: Add deal.number with backfill
--   C1: Fix onDelete for stage relations (Cascade → Restrict/SetNull)
-- ============================================================================

-- ============================================================================
-- PART A1: Clean test data duplicates
-- ============================================================================

-- Delete duplicate crm_user_fields (keep the oldest one per clubId+entityType+fieldName)
DELETE FROM "crm_user_field_values"
WHERE "fieldId" IN (
  SELECT f.id FROM "crm_user_fields" f
  WHERE f.id NOT IN (
    SELECT DISTINCT ON ("clubId", "entityType", "fieldName") id
    FROM "crm_user_fields"
    ORDER BY "clubId", "entityType", "fieldName", "createdAt" ASC
  )
);

DELETE FROM "crm_user_fields"
WHERE id NOT IN (
  SELECT DISTINCT ON ("clubId", "entityType", "fieldName") id
  FROM "crm_user_fields"
  ORDER BY "clubId", "entityType", "fieldName", "createdAt" ASC
);

-- Delete empty test pipelines (no deals AND name contains "E2E" or "Test")
DELETE FROM "crm_stages"
WHERE "pipelineId" IN (
  SELECT p.id FROM "crm_pipelines" p
  LEFT JOIN "crm_deals" d ON d."pipelineId" = p.id
  WHERE (p.name ILIKE '%E2E%' OR p.name ILIKE '%test%')
  GROUP BY p.id
  HAVING COUNT(d.id) = 0
);

DELETE FROM "crm_pipelines"
WHERE id IN (
  SELECT p.id FROM "crm_pipelines" p
  LEFT JOIN "crm_deals" d ON d."pipelineId" = p.id
  LEFT JOIN "crm_stages" s ON s."pipelineId" = p.id
  WHERE (p.name ILIKE '%E2E%' OR p.name ILIKE '%test%')
  GROUP BY p.id
  HAVING COUNT(d.id) = 0 AND COUNT(s.id) = 0
);

-- Delete duplicate crm_lost_reasons (keep oldest per clubId+name)
DELETE FROM "crm_lost_reasons"
WHERE id NOT IN (
  SELECT DISTINCT ON ("clubId", "name") id
  FROM "crm_lost_reasons"
  ORDER BY "clubId", "name", "createdAt" ASC
);

-- ============================================================================
-- PART A2: Fix deals with NULL clubId — assign to first existing club
-- ============================================================================
UPDATE "crm_deals"
SET "clubId" = (SELECT id FROM "clubs" ORDER BY "createdAt" ASC LIMIT 1)
WHERE "clubId" IS NULL
  AND EXISTS (SELECT 1 FROM "clubs" LIMIT 1);

-- ============================================================================
-- PART B1-B2: Add number column + backfill
-- ============================================================================

-- Add nullable number column first
ALTER TABLE "crm_deals" ADD COLUMN "number" INTEGER;

-- Backfill: sequential numbers partitioned by clubId, ordered by createdAt
WITH numbered AS (
  SELECT id, ROW_NUMBER() OVER (PARTITION BY "clubId" ORDER BY "createdAt" ASC) AS rn
  FROM "crm_deals"
)
UPDATE "crm_deals" d
SET "number" = numbered.rn
FROM numbered
WHERE d.id = numbered.id;

-- Create unique index on (clubId, number)
CREATE UNIQUE INDEX "crm_deals_clubId_number_key" ON "crm_deals"("clubId", "number");

-- ============================================================================
-- PART C1: Fix onDelete constraints
-- ============================================================================

-- CrmDeal.stage: Cascade → Restrict
ALTER TABLE "crm_deals" DROP CONSTRAINT IF EXISTS "crm_deals_stageId_fkey";
ALTER TABLE "crm_deals" ADD CONSTRAINT "crm_deals_stageId_fkey"
  FOREIGN KEY ("stageId") REFERENCES "crm_stages"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- CrmStageHistory.toStage: Cascade → SetNull, make nullable
ALTER TABLE "crm_stage_history" ALTER COLUMN "toStageId" DROP NOT NULL;
ALTER TABLE "crm_stage_history" DROP CONSTRAINT IF EXISTS "crm_stage_history_toStageId_fkey";
ALTER TABLE "crm_stage_history" ADD CONSTRAINT "crm_stage_history_toStageId_fkey"
  FOREIGN KEY ("toStageId") REFERENCES "crm_stages"("id") ON DELETE SET NULL ON UPDATE CASCADE;
