CREATE TYPE "RecruitmentClientStatus" AS ENUM ('LEAD', 'ACTIVE', 'PROCESSING', 'ON_HOLD', 'APPROVED', 'COMPLETED', 'REJECTED', 'CANCELLED');

ALTER TABLE "agent_profiles"
  ADD COLUMN "agentCode" VARCHAR(30),
  ADD COLUMN "whatsapp" VARCHAR(30),
  ADD COLUMN "country" VARCHAR(100),
  ADD COLUMN "joiningDate" DATE,
  ADD COLUMN "notes" TEXT;

CREATE UNIQUE INDEX "agent_profiles_agentCode_key" ON "agent_profiles"("agentCode");

CREATE TABLE "recruitment_clients" (
  "id" UUID NOT NULL,
  "clientCode" VARCHAR(30) NOT NULL,
  "linkedUserId" UUID,
  "agentProfileId" UUID,
  "fullName" VARCHAR(150) NOT NULL,
  "passportNumber" VARCHAR(40),
  "passportExpiry" DATE,
  "dateOfBirth" DATE,
  "gender" VARCHAR(30),
  "email" VARCHAR(255),
  "phone" VARCHAR(30) NOT NULL,
  "whatsapp" VARCHAR(30),
  "nationality" VARCHAR(100),
  "presentAddress" TEXT,
  "permanentAddress" TEXT,
  "visaType" "VisaApplicationType",
  "destinationCountry" VARCHAR(100),
  "jobSkill" VARCHAR(160),
  "fileDate" DATE,
  "contractAmount" DECIMAL(14,2) NOT NULL DEFAULT 0,
  "currency" VARCHAR(3) NOT NULL DEFAULT 'BDT',
  "status" "RecruitmentClientStatus" NOT NULL DEFAULT 'ACTIVE',
  "notes" TEXT,
  "createdById" UUID,
  "updatedById" UUID,
  "createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updatedAt" TIMESTAMPTZ(3) NOT NULL,
  CONSTRAINT "recruitment_clients_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "recruitment_payments" (
  "id" UUID NOT NULL,
  "clientId" UUID NOT NULL,
  "amount" DECIMAL(14,2) NOT NULL,
  "currency" VARCHAR(3) NOT NULL DEFAULT 'BDT',
  "paidAt" TIMESTAMPTZ(3) NOT NULL,
  "method" VARCHAR(60) NOT NULL,
  "transactionRef" VARCHAR(120),
  "receiptNumber" VARCHAR(60),
  "note" TEXT,
  "recordedById" UUID,
  "createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updatedAt" TIMESTAMPTZ(3) NOT NULL,
  CONSTRAINT "recruitment_payments_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "recruitment_client_status_history" (
  "id" UUID NOT NULL,
  "clientId" UUID NOT NULL,
  "fromStatus" "RecruitmentClientStatus",
  "toStatus" "RecruitmentClientStatus" NOT NULL,
  "note" TEXT,
  "changedById" UUID,
  "createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT "recruitment_client_status_history_pkey" PRIMARY KEY ("id")
);

ALTER TABLE "visa_applications" ADD COLUMN "recruitmentClientId" UUID;

CREATE UNIQUE INDEX "recruitment_clients_clientCode_key" ON "recruitment_clients"("clientCode");
CREATE UNIQUE INDEX "recruitment_clients_linkedUserId_key" ON "recruitment_clients"("linkedUserId");
CREATE UNIQUE INDEX "recruitment_clients_passportNumber_key" ON "recruitment_clients"("passportNumber");
CREATE INDEX "recruitment_clients_agentProfileId_status_idx" ON "recruitment_clients"("agentProfileId", "status");
CREATE INDEX "recruitment_clients_status_fileDate_idx" ON "recruitment_clients"("status", "fileDate");
CREATE INDEX "recruitment_clients_fullName_idx" ON "recruitment_clients"("fullName");
CREATE INDEX "recruitment_clients_phone_idx" ON "recruitment_clients"("phone");
CREATE UNIQUE INDEX "recruitment_payments_receiptNumber_key" ON "recruitment_payments"("receiptNumber");
CREATE INDEX "recruitment_payments_clientId_paidAt_idx" ON "recruitment_payments"("clientId", "paidAt");
CREATE INDEX "recruitment_payments_recordedById_idx" ON "recruitment_payments"("recordedById");
CREATE INDEX "recruitment_client_status_history_clientId_createdAt_idx" ON "recruitment_client_status_history"("clientId", "createdAt");
CREATE INDEX "recruitment_client_status_history_changedById_idx" ON "recruitment_client_status_history"("changedById");
CREATE INDEX "visa_applications_recruitmentClientId_idx" ON "visa_applications"("recruitmentClientId");

ALTER TABLE "recruitment_clients" ADD CONSTRAINT "recruitment_clients_linkedUserId_fkey" FOREIGN KEY ("linkedUserId") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "recruitment_clients" ADD CONSTRAINT "recruitment_clients_agentProfileId_fkey" FOREIGN KEY ("agentProfileId") REFERENCES "agent_profiles"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "recruitment_clients" ADD CONSTRAINT "recruitment_clients_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "recruitment_clients" ADD CONSTRAINT "recruitment_clients_updatedById_fkey" FOREIGN KEY ("updatedById") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "recruitment_payments" ADD CONSTRAINT "recruitment_payments_clientId_fkey" FOREIGN KEY ("clientId") REFERENCES "recruitment_clients"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "recruitment_payments" ADD CONSTRAINT "recruitment_payments_recordedById_fkey" FOREIGN KEY ("recordedById") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "recruitment_client_status_history" ADD CONSTRAINT "recruitment_client_status_history_clientId_fkey" FOREIGN KEY ("clientId") REFERENCES "recruitment_clients"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "recruitment_client_status_history" ADD CONSTRAINT "recruitment_client_status_history_changedById_fkey" FOREIGN KEY ("changedById") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "visa_applications" ADD CONSTRAINT "visa_applications_recruitmentClientId_fkey" FOREIGN KEY ("recruitmentClientId") REFERENCES "recruitment_clients"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- Bring existing registered client profiles into the management system without changing their login accounts.
INSERT INTO "recruitment_clients" (
  "id", "clientCode", "linkedUserId", "agentProfileId", "fullName", "email", "phone",
  "presentAddress", "fileDate", "contractAmount", "currency", "status", "createdAt", "updatedAt"
)
SELECT
  md5(cp."id"::text || ':euroquest-recruitment-client')::uuid,
  'EQC-' || upper(substr(replace(cp."id"::text, '-', ''), 1, 8)),
  cp."userId",
  cp."agentId",
  cp."fullName",
  u."email",
  cp."phone",
  cp."address",
  cp."createdAt"::date,
  0,
  'BDT',
  'ACTIVE'::"RecruitmentClientStatus",
  cp."createdAt",
  cp."updatedAt"
FROM "client_profiles" cp
JOIN "users" u ON u."id" = cp."userId"
ON CONFLICT ("linkedUserId") DO NOTHING;

-- Link existing visa applications to the backfilled management client record.
UPDATE "visa_applications" va
SET "recruitmentClientId" = rc."id"
FROM "recruitment_clients" rc
WHERE rc."linkedUserId" = va."clientId"
  AND va."recruitmentClientId" IS NULL;
