import { Router } from "express";
import { z } from "zod";
import { prisma } from "../prisma.js";
import { requireAuth, type AuthedRequest } from "../middleware/auth.js";
import { requirePermission } from "../middleware/permissions.js";
import { hasProjectAccess } from "../services/scopePolicy.js";
import { writeAuditEvent } from "../services/auditEventService.js";
import {
  canonicalPhoneKey,
  isScientificNotationPhone,
  isValidEthiopianMobilePhone,
  normalizePhone,
  phonePrimaryValidationError,
} from "../services/phoneNormalize.js";

const router = Router();
router.use(requireAuth);

function asId(v: bigint) {
  return v.toString();
}

function buildName(firstName: string, fatherName: string | null, grandfatherName: string | null) {
  return [firstName, fatherName ?? "", grandfatherName ?? ""].join(" ").replace(/\s+/g, " ").trim();
}

type PhoneField = "phone_primary" | "phone_alternative";

function isBadScientificPhone(value: string | null | undefined): boolean {
  return isScientificNotationPhone(value);
}

async function findConflictingTraineeByPhoneAnyField(args: {
  projectId: bigint;
  phone: string;
  excludeTraineeId?: bigint;
}): Promise<{ id: bigint; firstName: string; field: PhoneField; stored: string } | null> {
  const key = canonicalPhoneKey(args.phone);
  if (!key) return null;
  const rows = await prisma.trainee.findMany({
    where: {
      projectId: args.projectId,
      ...(args.excludeTraineeId ? { id: { not: args.excludeTraineeId } } : {}),
      OR: [{ phonePrimary: { not: null } }, { phoneAlternative: { not: null } }],
    },
    select: {
      id: true,
      firstName: true,
      fatherName: true,
      phonePrimary: true,
      phoneAlternative: true,
    },
    take: 10000,
  });
  for (const r of rows) {
    if (r.phonePrimary && canonicalPhoneKey(r.phonePrimary) === key) {
      return {
        id: r.id,
        firstName: [r.firstName, r.fatherName].filter(Boolean).join(" "),
        field: "phone_primary",
        stored: r.phonePrimary,
      };
    }
    if (r.phoneAlternative && canonicalPhoneKey(r.phoneAlternative) === key) {
      return {
        id: r.id,
        firstName: [r.firstName, r.fatherName].filter(Boolean).join(" "),
        field: "phone_alternative",
        stored: r.phoneAlternative,
      };
    }
  }
  return null;
}

function correctedPhoneValidationError(value: unknown, field: PhoneField): string | null {
  const raw = String(value ?? "").trim();
  if (!raw) return `Missing ${field}`;
  if (isScientificNotationPhone(raw)) {
    return `Invalid ${field} (scientific notation is not allowed)`;
  }
  if (!/^\d+$/.test(raw.replace(/\s/g, "")) && !isValidEthiopianMobilePhone(raw)) {
    const normalized = normalizePhone(raw);
    if (!/^\d{9}$/.test(normalized) || !normalized.startsWith("9")) {
      return `Invalid ${field} (must be digits only, valid Ethiopian mobile e.g. 0911223344)`;
    }
  }
  if (field === "phone_primary") {
    const primaryErr = phonePrimaryValidationError(raw);
    if (primaryErr) return primaryErr.replace("phonePrimary", "phone_primary");
  } else if (!isValidEthiopianMobilePhone(raw)) {
    return "Invalid phone_alternative (must be a valid Ethiopian mobile number)";
  }
  return null;
}

router.get(
  "/projects/:projectId/admin/phone-correction",
  requirePermission("admin:phone-correction", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(prisma, projectId, req.auth!.userId))) {
      return void res.status(403).json({ error: "No access." });
    }
    const providerQ =
      typeof req.query.trainingProviderId === "string" && /^\d+$/.test(req.query.trainingProviderId)
        ? BigInt(req.query.trainingProviderId)
        : typeof req.query.provider_id === "string" && /^\d+$/.test(req.query.provider_id)
          ? BigInt(req.query.provider_id)
          : null;
    if (!providerQ) {
      return void res.status(400).json({ error: "trainingProviderId (or provider_id) is required." });
    }

    const provider = await prisma.trainingProvider.findFirst({
      where: { id: providerQ, projectId },
      select: { id: true, tpCode: true, name: true },
    });
    if (!provider) return void res.status(404).json({ error: "Training provider not found." });

    const trainees = await prisma.trainee.findMany({
      where: { projectId, trainingProviderId: providerQ },
      select: {
        id: true,
        traineeUniqueId: true,
        firstName: true,
        fatherName: true,
        grandfatherName: true,
        sex: true,
        ageYears: true,
        phonePrimary: true,
        phoneAlternative: true,
      },
      orderBy: [{ firstName: "asc" }, { id: "asc" }],
    });

    const items: Array<{
      traineeId: string;
      traineeUniqueId: string;
      fullName: string;
      firstName: string;
      fatherName: string | null;
      grandfatherName: string | null;
      sex: string | null;
      ageYears: number | null;
      field: PhoneField;
      badPhone: string;
    }> = [];

    for (const t of trainees) {
      if (isBadScientificPhone(t.phonePrimary)) {
        items.push({
          traineeId: asId(t.id),
          traineeUniqueId: t.traineeUniqueId,
          fullName: buildName(t.firstName, t.fatherName, t.grandfatherName),
          firstName: t.firstName,
          fatherName: t.fatherName,
          grandfatherName: t.grandfatherName,
          sex: t.sex,
          ageYears: t.ageYears,
          field: "phone_primary",
          badPhone: t.phonePrimary!,
        });
      }
      if (isBadScientificPhone(t.phoneAlternative)) {
        items.push({
          traineeId: asId(t.id),
          traineeUniqueId: t.traineeUniqueId,
          fullName: buildName(t.firstName, t.fatherName, t.grandfatherName),
          firstName: t.firstName,
          fatherName: t.fatherName,
          grandfatherName: t.grandfatherName,
          sex: t.sex,
          ageYears: t.ageYears,
          field: "phone_alternative",
          badPhone: t.phoneAlternative!,
        });
      }
    }

    res.json({
      provider: { id: asId(provider.id), tpCode: provider.tpCode, name: provider.name },
      items,
      total: items.length,
    });
  },
);

router.patch(
  "/projects/:projectId/admin/phone-correction/:traineeId",
  requirePermission("admin:phone-correction", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const traineeId = BigInt(req.params.traineeId);
    if (!(await hasProjectAccess(prisma, projectId, req.auth!.userId))) {
      return void res.status(403).json({ error: "No access." });
    }

    const parsed = z
      .object({
        field: z.enum(["phone_primary", "phone_alternative"]),
        correctedPhone: z.string().min(1).max(100),
      })
      .safeParse(req.body);
    if (!parsed.success) {
      return void res.status(400).json({ error: "Invalid body", details: parsed.error.flatten() });
    }

    const field = parsed.data.field;
    const validationErr = correctedPhoneValidationError(parsed.data.correctedPhone, field);
    if (validationErr) {
      return void res.status(422).json({ error: validationErr });
    }

    const normalized = normalizePhone(parsed.data.correctedPhone);
    const conflict = await findConflictingTraineeByPhoneAnyField({
      projectId,
      phone: normalized,
      excludeTraineeId: traineeId,
    });
    if (conflict) {
      return void res.status(409).json({
        error: `Phone already exists in this project (${conflict.firstName}, ${conflict.field}: ${conflict.stored}).`,
      });
    }

    const trainee = await prisma.trainee.findFirst({
      where: { id: traineeId, projectId },
      select: {
        id: true,
        trainingProviderId: true,
        trainingId: true,
        cohortId: true,
        batchId: true,
        phonePrimary: true,
        phoneAlternative: true,
      },
    });
    if (!trainee) return void res.status(404).json({ error: "Trainee not found." });

    const oldValue = field === "phone_primary" ? trainee.phonePrimary : trainee.phoneAlternative;
    const updateData =
      field === "phone_primary"
        ? { phonePrimary: normalized }
        : { phoneAlternative: normalized };

    const updated = await prisma.trainee.update({
      where: { id: traineeId },
      data: updateData,
      select: {
        id: true,
        traineeUniqueId: true,
        firstName: true,
        phonePrimary: true,
        phoneAlternative: true,
      },
    });

    await writeAuditEvent({
      projectId,
      trainingProviderId: trainee.trainingProviderId,
      trainingId: trainee.trainingId,
      cohortId: trainee.cohortId,
      batchId: trainee.batchId,
      module: "domain",
      action: "trainee_phone_corrected",
      sourceType: "trainee",
      sourceRef: traineeId.toString(),
      actorUserId: req.auth!.userId,
      meta: {
        field,
        oldValue,
        newValue: normalized,
      },
    });

    res.json({
      item: {
        traineeId: asId(updated.id),
        traineeUniqueId: updated.traineeUniqueId,
        firstName: updated.firstName,
        phonePrimary: updated.phonePrimary,
        phoneAlternative: updated.phoneAlternative,
        field,
        correctedPhone: normalized,
      },
    });
  },
);

export default router;
