ALTER TABLE "crm_enquiries"
ADD COLUMN "pipeline_stage" text;

UPDATE "crm_enquiries" AS enquiry
SET "pipeline_stage" = CASE
  WHEN EXISTS (
    SELECT 1
    FROM "ms_options" AS option
    WHERE option."id" = enquiry."status"
      AND option."category" = 'crm_enquiry_status'
      AND option."code" IN ('closed_lost', 'cancelled')
      AND option."deleted_at" IS NULL
  ) THEN 'closed_lost'
  WHEN enquiry."assigned_to_user_id" IS NOT NULL THEN 'enquiry'
  ELSE 'lead'
END
WHERE enquiry."pipeline_stage" IS NULL;

UPDATE "crm_enquiries"
SET "pipeline_stage" = 'lead'
WHERE "pipeline_stage" IS NULL;

ALTER TABLE "crm_enquiries"
ALTER COLUMN "pipeline_stage" SET DEFAULT 'lead';

ALTER TABLE "crm_enquiries"
ALTER COLUMN "pipeline_stage" SET NOT NULL;

ALTER TABLE "crm_enquiries"
ADD CONSTRAINT "crm_enquiries_pipeline_stage_check"
CHECK ("pipeline_stage" IN ('lead', 'enquiry', 'closed_won', 'closed_lost'));
