import { Router } from "express";
import { prisma } from "../prisma.js";
import {
  blankToUndefined,
  parseIdParam,
  publicFeedbackSchema,
  publicFormLimiter,
  publicSubmitLimiter,
} from "../lib/publicInput.js";
import { sendPublicFeedbackAcknowledgement } from "../services/smtp.js";

const router = Router();

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

router.get("/projects", publicFormLimiter, async (_req, res) => {
  const items = await prisma.project.findMany({
    select: { id: true, projectCode: true, title: true },
    orderBy: { id: "desc" },
    take: 100,
  });
  res.json({ items: items.map((x) => ({ id: asId(x.id), code: x.projectCode, title: x.title })) });
});

router.get("/projects/:projectId/providers", publicFormLimiter, async (req, res) => {
  const projectId = parseIdParam(req.params.projectId ?? "");
  if (!projectId) return void res.status(400).json({ error: "Invalid project." });
  const items = await prisma.trainingProvider.findMany({
    where: { projectId },
    select: { id: true, tpCode: true, name: true },
    orderBy: { name: "asc" },
  });
  res.json({ items: items.map((x) => ({ id: asId(x.id), tpCode: x.tpCode, name: x.name })) });
});

router.get("/locations", publicFormLimiter, async (_req, res) => {
  const items = await prisma.location.findMany({
    where: { isActive: true },
    select: { id: true, name: true, code: true },
    orderBy: { name: "asc" },
  });
  res.json({ items: items.map((x) => ({ id: asId(x.id), name: x.name, code: x.code })) });
});

router.post("/projects/:projectId/feedback", publicSubmitLimiter, async (req, res) => {
  const projectId = parseIdParam(req.params.projectId ?? "");
  if (!projectId) return void res.status(400).json({ error: "Invalid project." });

  const parsed = publicFeedbackSchema.safeParse({
    ...(typeof req.body === "object" && req.body !== null ? req.body : {}),
    region: blankToUndefined((req.body as Record<string, unknown> | undefined)?.region),
  });
  if (!parsed.success) {
    return void res.status(400).json({
      error: "Invalid request",
      details: parsed.error.flatten(),
      fieldErrors: parsed.error.issues.map((i) => ({ field: i.path.join("."), message: i.message })),
    });
  }

  const data = parsed.data;
  const tpId = BigInt(data.trainingProviderId);
  const tp = await prisma.trainingProvider.findFirst({
    where: { id: tpId, projectId },
    select: { id: true, name: true },
  });
  if (!tp) return void res.status(404).json({ error: "Training Provider not found in this project." });

  const now = new Date();
  const dueAt = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
  const refCode = `GRM-${now.getUTCFullYear()}-${Date.now().toString().slice(-6)}`;

  const created = await prisma.feedbackThread.create({
    data: {
      projectId,
      trainingProviderId: tpId,
      refCode,
      category: data.category,
      subject: data.subject,
      description: data.description,
      submitterName: data.submitterName,
      submitterEmail: data.submitterEmail,
      submitterPhone: data.submitterPhone || null,
      region: data.region || null,
      status: "open",
      submittedAt: now,
      dueAt,
      messages: {
        create: {
          authorType: "public",
          authorName: data.submitterName,
          body: data.description,
          sentToSubmitter: false,
        },
      },
    },
    select: { id: true, refCode: true },
  });

  void sendPublicFeedbackAcknowledgement(prisma, {
    to: data.submitterEmail,
    submitterName: data.submitterName,
    category: data.category,
    referenceCode: created.refCode,
    providerName: tp.name,
    subject: data.subject,
    dueAt,
  }).catch((error) => {
    const detail = error instanceof Error ? error.message : "unknown smtp error";
    console.error("[feedback/public] acknowledgement email failed:", detail);
  });

  res.status(201).json({ item: { id: asId(created.id), ref: created.refCode } });
});

export default router;
