-- CreateEnum
CREATE TYPE "BusinessRole" AS ENUM ('SENIOR_PARTNER', 'JUNIOR_PARTNER', 'MANAGEMENT', 'PARALEGAL', 'CLIENT');

-- CreateEnum
CREATE TYPE "FirmCaseStage" AS ENUM ('INSTRUCTIONS_INTAKE', 'APPROVAL_DOCUMENT_COLLECTION', 'CASE_PREPARATION_FILING', 'MENTIONS', 'HEARING', 'JUDGMENT', 'PAYMENT_EXECUTION', 'CLIENT_REMITTANCE', 'CLOSED', 'DECLINED', 'REFERRED');

-- CreateEnum
CREATE TYPE "CaseCategory" AS ENUM ('PERSONAL_INJURY', 'COMMERCIAL');

-- CreateEnum
CREATE TYPE "CostTreatment" AS ENUM ('RECOVERABLE_FROM_CLIENT', 'RECOVERABLE_FROM_PROCEEDS', 'NON_RECOVERABLE_FIRM_EXPENSE', 'USER_DECISION_REQUIRED');

-- CreateEnum
CREATE TYPE "CaseCostStatus" AS ENUM ('EXPECTED', 'REQUEST_PREPARED', 'SUBMITTED', 'APPROVED', 'REJECTED', 'PARTIALLY_PAID', 'PAID', 'RECOVERABLE', 'RECOVERED', 'WRITTEN_OFF', 'WAIVED', 'NOT_APPLICABLE', 'REVERSED');

-- CreateEnum
CREATE TYPE "ExpenseRequestStatus" AS ENUM ('PREPARED', 'SUBMITTED', 'APPROVED', 'REJECTED', 'PAID', 'REVERSED');

-- AlterEnum
-- This migration adds more than one value to an enum.
-- With PostgreSQL versions 11 and earlier, this is not possible
-- in a single migration. This can be worked around by creating
-- multiple migrations, each migration adding only one value to
-- the enum.


ALTER TYPE "Role" ADD VALUE 'SENIOR_PARTNER';
ALTER TYPE "Role" ADD VALUE 'JUNIOR_PARTNER';
ALTER TYPE "Role" ADD VALUE 'MANAGEMENT';
ALTER TYPE "Role" ADD VALUE 'PARALEGAL';

-- AlterTable
ALTER TABLE "cases" ADD COLUMN     "caseTypeId" TEXT,
ADD COLUMN     "firmStage" "FirmCaseStage" NOT NULL DEFAULT 'INSTRUCTIONS_INTAKE';

-- AlterTable
ALTER TABLE "users" ADD COLUMN     "isSystemAdmin" BOOLEAN NOT NULL DEFAULT false;

-- CreateTable
CREATE TABLE "user_role_assignments" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "role" "BusinessRole" NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "firm_profiles" (
    "id" TEXT NOT NULL,
    "legalName" TEXT NOT NULL DEFAULT 'Kariuki Kagunda and Company Advocates',
    "displayName" TEXT NOT NULL DEFAULT 'Kariuki Kagunda & Co. Advocates',
    "email" TEXT,
    "phone" TEXT,
    "address" TEXT,
    "registrationNumber" TEXT,
    "taxNumber" TEXT,
    "defaultCurrency" TEXT NOT NULL DEFAULT 'KES',
    "fiscalYearStartMonth" INTEGER NOT NULL DEFAULT 1,
    "documentHeader" TEXT,
    "emailSignature" TEXT,
    "portalBranding" JSONB,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "case_types" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "category" "CaseCategory" NOT NULL,
    "name" TEXT NOT NULL,
    "description" TEXT,
    "specialistWorkflow" JSONB,
    "isActive" BOOLEAN NOT NULL DEFAULT true,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "expected_cost_templates" (
    "id" TEXT NOT NULL,
    "caseTypeId" TEXT NOT NULL,
    "stage" "FirmCaseStage" NOT NULL,
    "name" TEXT NOT NULL,
    "description" TEXT,
    "payeeCategory" TEXT,
    "suggestedAmount" DECIMAL(14,2),
    "treatment" "CostTreatment" NOT NULL DEFAULT 'USER_DECISION_REQUIRED',
    "supportingDocumentRequired" BOOLEAN NOT NULL DEFAULT true,
    "mandatoryBeforeStageCompletion" BOOLEAN NOT NULL DEFAULT true,
    "multiplePaymentsAllowed" BOOLEAN NOT NULL DEFAULT false,
    "expenseAccountCode" TEXT,
    "taxCode" TEXT,
    "isActive" BOOLEAN NOT NULL DEFAULT true,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "case_cost_requirements" (
    "id" TEXT NOT NULL,
    "caseId" TEXT NOT NULL,
    "templateId" TEXT,
    "stage" "FirmCaseStage" NOT NULL,
    "name" TEXT NOT NULL,
    "description" TEXT,
    "treatment" "CostTreatment" NOT NULL,
    "mandatory" BOOLEAN NOT NULL DEFAULT true,
    "status" "CaseCostStatus" NOT NULL DEFAULT 'EXPECTED',
    "expectedAmount" DECIMAL(14,2),
    "paidAmount" DECIMAL(14,2) NOT NULL DEFAULT 0,
    "recoveredAmount" DECIMAL(14,2) NOT NULL DEFAULT 0,
    "waiverReason" TEXT,
    "waivedBy" TEXT,
    "waivedAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "expense_requests" (
    "id" TEXT NOT NULL,
    "requirementId" TEXT NOT NULL,
    "preparedBy" TEXT NOT NULL,
    "approvedBy" TEXT,
    "vendorName" TEXT NOT NULL,
    "purpose" TEXT NOT NULL,
    "amount" DECIMAL(14,2) NOT NULL,
    "taxAmount" DECIMAL(14,2) NOT NULL DEFAULT 0,
    "paymentMethod" TEXT,
    "supportingReference" TEXT,
    "treatment" "CostTreatment" NOT NULL,
    "status" "ExpenseRequestStatus" NOT NULL DEFAULT 'PREPARED',
    "submittedAt" TIMESTAMP(3),
    "approvedAt" TIMESTAMP(3),
    "rejectedAt" TIMESTAMP(3),
    "rejectionReason" TEXT,
    "paidAt" TIMESTAMP(3),
    "paymentReference" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "case_stage_transitions" (
    "id" TEXT NOT NULL,
    "caseId" TEXT NOT NULL,
    "fromStage" "FirmCaseStage" NOT NULL,
    "toStage" "FirmCaseStage" NOT NULL,
    "reason" TEXT NOT NULL,
    "transitionedBy" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateIndex
CREATE INDEX "user_role_assignments_role_idx" ON "user_role_assignments"("role");

-- CreateIndex
CREATE UNIQUE INDEX "user_role_assignments_userId_role_key" ON "user_role_assignments"("userId", "role");

-- CreateIndex
CREATE UNIQUE INDEX "case_types_code_key" ON "case_types"("code");

-- CreateIndex
CREATE INDEX "case_types_category_isActive_idx" ON "case_types"("category", "isActive");

-- CreateIndex
CREATE INDEX "expected_cost_templates_caseTypeId_stage_idx" ON "expected_cost_templates"("caseTypeId", "stage");

-- CreateIndex
CREATE UNIQUE INDEX "expected_cost_templates_caseTypeId_stage_name_key" ON "expected_cost_templates"("caseTypeId", "stage", "name");

-- CreateIndex
CREATE INDEX "case_cost_requirements_caseId_stage_status_idx" ON "case_cost_requirements"("caseId", "stage", "status");

-- CreateIndex
CREATE INDEX "expense_requests_requirementId_status_idx" ON "expense_requests"("requirementId", "status");

-- CreateIndex
CREATE INDEX "expense_requests_status_submittedAt_idx" ON "expense_requests"("status", "submittedAt");

-- CreateIndex
CREATE INDEX "case_stage_transitions_caseId_createdAt_idx" ON "case_stage_transitions"("caseId", "createdAt");

-- CreateIndex
CREATE INDEX "cases_caseTypeId_idx" ON "cases"("caseTypeId");

-- CreateIndex
CREATE INDEX "cases_firmStage_idx" ON "cases"("firmStage");

-- AddForeignKey
ALTER TABLE "user_role_assignments" ADD CONSTRAINT "user_role_assignments_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "cases" ADD CONSTRAINT "cases_caseTypeId_fkey" FOREIGN KEY ("caseTypeId") REFERENCES "case_types"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "expected_cost_templates" ADD CONSTRAINT "expected_cost_templates_caseTypeId_fkey" FOREIGN KEY ("caseTypeId") REFERENCES "case_types"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "case_cost_requirements" ADD CONSTRAINT "case_cost_requirements_caseId_fkey" FOREIGN KEY ("caseId") REFERENCES "cases"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "case_cost_requirements" ADD CONSTRAINT "case_cost_requirements_templateId_fkey" FOREIGN KEY ("templateId") REFERENCES "expected_cost_templates"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "case_cost_requirements" ADD CONSTRAINT "case_cost_requirements_waivedBy_fkey" FOREIGN KEY ("waivedBy") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "expense_requests" ADD CONSTRAINT "expense_requests_requirementId_fkey" FOREIGN KEY ("requirementId") REFERENCES "case_cost_requirements"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "expense_requests" ADD CONSTRAINT "expense_requests_preparedBy_fkey" FOREIGN KEY ("preparedBy") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "expense_requests" ADD CONSTRAINT "expense_requests_approvedBy_fkey" FOREIGN KEY ("approvedBy") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "case_stage_transitions" ADD CONSTRAINT "case_stage_transitions_caseId_fkey" FOREIGN KEY ("caseId") REFERENCES "cases"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "case_stage_transitions" ADD CONSTRAINT "case_stage_transitions_transitionedBy_fkey" FOREIGN KEY ("transitionedBy") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- Seed the configured firm and migrate legacy business roles without losing system administration.
INSERT INTO "firm_profiles" ("id", "legalName", "displayName", "defaultCurrency", "fiscalYearStartMonth", "createdAt", "updatedAt")
VALUES (gen_random_uuid()::text, 'Kariuki Kagunda and Company Advocates', 'Kariuki Kagunda & Co. Advocates', 'KES', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);

UPDATE "users" SET "isSystemAdmin" = true WHERE "role" = 'ADMIN';

INSERT INTO "user_role_assignments" ("id", "userId", "role", "createdAt")
SELECT gen_random_uuid()::text, "id",
  CASE "role"::text
    WHEN 'ADMIN' THEN 'MANAGEMENT'::"BusinessRole"
    WHEN 'PARTNER' THEN 'SENIOR_PARTNER'::"BusinessRole"
    WHEN 'COLLABORATOR' THEN 'PARALEGAL'::"BusinessRole"
    WHEN 'SENIOR_PARTNER' THEN 'SENIOR_PARTNER'::"BusinessRole"
    WHEN 'JUNIOR_PARTNER' THEN 'JUNIOR_PARTNER'::"BusinessRole"
    WHEN 'MANAGEMENT' THEN 'MANAGEMENT'::"BusinessRole"
    WHEN 'PARALEGAL' THEN 'PARALEGAL'::"BusinessRole"
    ELSE 'CLIENT'::"BusinessRole"
  END,
  CURRENT_TIMESTAMP
FROM "users";
