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 {
  buildGenericNoticeEmailContent,
  createTransportFromConfig,
  sendFeedbackResponseEmailWithTpSmtp,
  sendPublicFeedbackAcknowledgement,
  sendNewFeedbackNotificationToProvider,
} from "../services/smtp.js";
import { computeFeedbackMetrics, derivedStatus } from "../services/feedbackMetrics.js";
import {
  blankToUndefined,
  emailField,
  feedbackReplyBodyField,
  parseIdParam,
  publicFeedbackSchema,
  publicFormLimiter,
  publicSubmitLimiter,
  textField,
} from "../lib/publicInput.js";
import {
  hasProjectAccess as hasProjectAccessPolicy,
  resolveProjectScope as resolveProjectScopePolicy,
} from "../services/scopePolicy.js";

const router = Router();

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

function redactedEmail(email: string): string {
  const [name, domain] = email.split("@");
  if (!domain) return "***";
  const prefix = name.length <= 2 ? `${name[0] ?? "*"}*` : `${name.slice(0, 2)}***`;
  return `${prefix}@${domain}`;
}

function redactedPhone(phone: string): string {
  const clean = phone.replace(/\s+/g, "");
  if (clean.length < 5) return "***";
  return `${clean.slice(0, 2)}***${clean.slice(-2)}`;
}

function smtpErrorMessage(e: unknown): string {
  const raw = e instanceof Error ? e.message : "SMTP connection failed.";
  if (raw.includes("ETIMEDOUT")) {
    return "SMTP connection timed out. Check host/firewall and prefer port 587 with TLS if 465 is blocked.";
  }
  if (raw.includes("ECONNREFUSED")) {
    return "SMTP connection was refused. Verify host, port, and encryption settings.";
  }
  if (raw.includes("ENOTFOUND")) {
    return "SMTP host not found. Verify SMTP host DNS value.";
  }
  if (raw.includes("EAUTH")) {
    return "SMTP authentication failed. Verify username/password and sender identity.";
  }
  return raw || "SMTP connection failed.";
}

async function hasProjectAccess(projectId: bigint, userId: bigint): Promise<boolean> {
  return hasProjectAccessPolicy(prisma, projectId, userId);
}

async function resolveScope(projectId: bigint, userId: bigint) {
  return resolveProjectScopePolicy(prisma, projectId, userId);
}

function toThreadDto(
  item: {
    id: bigint;
    projectId: bigint;
    trainingProviderId: bigint;
    refCode: string;
    category: string;
    subject: string;
    description: string;
    submitterName: string;
    submitterEmail: string;
    submitterPhone: string | null;
    region: string | null;
    status: string;
    submittedAt: Date;
    dueAt: Date;
    firstTpResponseAt: Date | null;
    resolvedAt: Date | null;
    createdAt: Date;
    updatedAt: Date;
    trainingProvider: { id: bigint; tpCode: string; name: string };
    messages: Array<{
      id: bigint;
      authorType: string;
      authorName: string;
      body: string;
      sentToSubmitter: boolean;
      emailSentAt: Date | null;
      emailError: string | null;
      createdAt: Date;
    }>;
  },
  redactSubmitter: boolean
) {
  // Self-heal: rows created before firstTpResponseAt existed still have their first
  // staff reply in the thread, so status/timeliness stay correct for old data.
  const firstStaffReplyAt = item.messages.find((m) => m.authorType !== "public")?.createdAt ?? null;
  const effectiveResponseAt = item.firstTpResponseAt ?? firstStaffReplyAt;
  return {
    id: asId(item.id),
    ref: item.refCode,
    projectId: asId(item.projectId),
    trainingProviderId: asId(item.trainingProviderId),
    trainingProvider: {
      id: asId(item.trainingProvider.id),
      tpCode: item.trainingProvider.tpCode,
      name: item.trainingProvider.name,
    },
    category: item.category,
    subject: item.subject,
    description: item.description,
    submitterName: redactSubmitter ? "Confidential" : item.submitterName,
    submitterEmail: redactSubmitter ? "***@***" : item.submitterEmail,
    submitterPhone: redactSubmitter ? null : item.submitterPhone,
    region: redactSubmitter ? null : item.region,
    // Status is derived from the first response timestamp so rows created before the
    // manual dropdown was removed still read correctly.
    status: derivedStatus({ dueAt: item.dueAt, firstTpResponseAt: item.firstTpResponseAt, firstStaffReplyAt }),
    submittedAt: item.submittedAt.toISOString(),
    dueAt: item.dueAt.toISOString(),
    firstTpResponseAt: effectiveResponseAt?.toISOString() ?? null,
    resolvedAt: item.resolvedAt?.toISOString() ?? null,
    createdAt: item.createdAt.toISOString(),
    updatedAt: item.updatedAt.toISOString(),
    messages: item.messages.map((m) => ({
      id: asId(m.id),
      authorType: m.authorType,
      authorName: m.authorName,
      body: m.body,
      sentToSubmitter: m.sentToSubmitter,
      emailSentAt: m.emailSentAt?.toISOString() ?? null,
      emailError: m.emailError,
      createdAt: m.createdAt.toISOString(),
    })),
  };
}

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

router.get("/public/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("/public/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("/public/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 },
  });

  // Acknowledgement email should not block submission success.
  void sendPublicFeedbackAcknowledgement(prisma, {
    to: data.submitterEmail,
    submitterName: data.submitterName,
    category: data.category,
    referenceCode: created.refCode,
    providerName: tp.name,
    subject: data.subject,
    dueAt,
  }).catch((error) => {
    console.error("[feedback/public] acknowledgement email failed:", smtpErrorMessage(error));
  });

  // Notify training provider about new feedback submission
  void sendNewFeedbackNotificationToProvider(prisma, {
    projectId,
    trainingProviderId: tpId,
    referenceCode: created.refCode,
    category: data.category,
    subject: data.subject,
    submitterName: data.submitterName,
    submittedAt: now,
    dueAt,
  }).catch((error) => {
    console.error("[feedback/public] provider notification failed:", smtpErrorMessage(error));
  });

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

router.use(requireAuth);

router.get(
  "/projects/:projectId/feedback",
  requirePermission("view:feedback", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    if (scope.role === "tp" && !scope.providerId) return void res.status(403).json({ error: "No TP provider assignment found for current user." });
    // Hide personal data from TP users only. Admin/M&E can see everything.
    const redactSubmitter = scope.role === "tp";
    const items = await prisma.feedbackThread.findMany({
      where: { projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
      include: {
        trainingProvider: { select: { id: true, tpCode: true, name: true } },
        messages: {
          orderBy: { createdAt: "asc" },
          select: {
            id: true,
            authorType: true,
            authorName: true,
            body: true,
            sentToSubmitter: true,
            emailSentAt: true,
            emailError: true,
            createdAt: true,
          },
        },
      },
      orderBy: { id: "desc" },
    });
    res.json({ items: items.map((x) => toThreadDto(x, redactSubmitter)) });
  }
);

/**
 * Aggregated GRM metrics over the FULL register (never truncated) plus a
 * per-training-provider timeliness breakdown. Feeds the KPI cards so the numbers
 * always agree with the grievance indicator.
 */
router.get(
  "/projects/:projectId/feedback/summary",
  requirePermission("view:feedback", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    if (scope.role === "tp" && !scope.providerId) return void res.status(403).json({ error: "No TP provider assignment found for current user." });

    const threads = await prisma.feedbackThread.findMany({
      where: { projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
      select: {
        trainingProviderId: true,
        dueAt: true,
        firstTpResponseAt: true,
        trainingProvider: { select: { tpCode: true, name: true } },
        messages: {
          where: { authorType: { in: ["admin", "tp"] } },
          orderBy: { createdAt: "asc" },
          take: 1,
          select: { authorType: true, createdAt: true },
        },
      },
    });

    res.json(computeFeedbackMetrics(threads, new Date()));
  }
);

router.get(
  "/projects/:projectId/feedback/:feedbackId",
  requirePermission("view:feedback", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const feedbackId = BigInt(req.params.feedbackId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    const item = await prisma.feedbackThread.findFirst({
      where: { id: feedbackId, projectId },
      include: {
        trainingProvider: { select: { id: true, tpCode: true, name: true } },
        messages: {
          orderBy: { createdAt: "asc" },
          select: {
            id: true,
            authorType: true,
            authorName: true,
            body: true,
            sentToSubmitter: true,
            emailSentAt: true,
            emailError: true,
            createdAt: true,
          },
        },
      },
    });
    if (!item) return void res.status(404).json({ error: "Feedback not found." });
    if (scope.providerId && item.trainingProviderId !== scope.providerId) return void res.status(403).json({ error: "No access to this feedback." });
    // Hide personal data from TP users only. Admin/M&E can see everything.
    const redactSubmitter = scope.role === "tp";
    res.json({ item: toThreadDto(item, redactSubmitter) });
  }
);

router.post(
  "/projects/:projectId/feedback/:feedbackId/replies",
  requirePermission("respond:feedback", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const feedbackId = BigInt(req.params.feedbackId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    const parsed = z
      .object({
        body: feedbackReplyBodyField,
        sendToSubmitter: z.boolean().default(false),
        useSystemSmtp: z.boolean().default(false),
      })
      .safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });

    const item = await prisma.feedbackThread.findFirst({
      where: { id: feedbackId, projectId },
      include: { trainingProvider: { select: { name: true } } },
    });
    if (!item) return void res.status(404).json({ error: "Feedback not found." });
    if (scope.providerId && item.trainingProviderId !== scope.providerId) return void res.status(403).json({ error: "No access to this feedback." });

    const actor = await prisma.user.findUnique({ where: { id: req.auth!.userId }, select: { name: true } });
    const now = new Date();

    if (parsed.data.sendToSubmitter) {
      try {
        await sendFeedbackResponseEmailWithTpSmtp(
          prisma,
          item.projectId,
          item.trainingProviderId,
          item.submitterEmail,
          `Feedback update (${item.refCode})`,
          parsed.data.body,
          parsed.data.useSystemSmtp
        );
      } catch (e: any) {
        // If it's a missing SMTP config error, return specific error code
        if (e.code === "NO_TP_SMTP_CONFIGURED") {
          return void res.status(422).json({ 
            error: "NO_TP_SMTP_CONFIGURED",
            message: "No SMTP configuration found for this training provider."
          });
        }
        if (e.code === "NO_SMTP_CONFIGURED") {
          return void res.status(422).json({ 
            error: "NO_SMTP_CONFIGURED",
            message: "No SMTP configuration available. Please contact administrator."
          });
        }
        return void res.status(422).json({ error: smtpErrorMessage(e) });
      }
    }

    const created = await prisma.feedbackMessage.create({
      data: {
        threadId: item.id,
        authorType: scope.role === "tp" ? "tp" : "admin",
        authorName: actor?.name ?? "Staff",
        body: parsed.data.body.trim(),
        sentToSubmitter: parsed.data.sendToSubmitter,
        emailSentAt: parsed.data.sendToSubmitter ? now : null,
      },
    });
    
    // The response date is the only signal that matters: the first reply stamps
    // firstTpResponseAt and automatically closes the case — there is no manual
    // status dropdown any more.
    await prisma.feedbackThread.update({
      where: { id: item.id },
      data: {
        ...(item.firstTpResponseAt ? {} : { firstTpResponseAt: now }),
        status: "resolved",
        resolvedAt: item.resolvedAt ?? now,
      },
    });
    res.status(201).json({
      item: {
        id: asId(created.id),
        authorType: created.authorType,
        authorName: created.authorName,
        body: created.body,
        sentToSubmitter: created.sentToSubmitter,
        emailSentAt: created.emailSentAt?.toISOString() ?? null,
        emailError: created.emailError,
        createdAt: created.createdAt.toISOString(),
      },
    });
  }
);

router.put(
  "/projects/:projectId/feedback/:feedbackId/status",
  requirePermission("respond:feedback", { projectIdParam: "projectId" }),
  async (_req: AuthedRequest, res) => {
    // Status is no longer manually editable: it is derived from the first response
    // timestamp. The endpoint is kept only so older clients get a clear message.
    res.status(410).json({
      error: "Manual status changes are no longer supported. A case is closed automatically as soon as a response is sent.",
    });
  }
);

function serializeTpSmtp(item: {
  id: bigint;
  senderName: string;
  senderEmail: string;
  smtpHost: string;
  smtpPort: string;
  smtpUser: string;
  smtpType: string;
  status: string;
  createdAt: Date;
  updatedAt: Date;
}) {
  return {
    id: asId(item.id),
    senderName: item.senderName,
    senderEmail: item.senderEmail,
    smtpHost: item.smtpHost,
    smtpPort: item.smtpPort,
    smtpUser: item.smtpUser,
    smtpType: item.smtpType,
    status: item.status,
    createdAt: item.createdAt.toISOString(),
    updatedAt: item.updatedAt.toISOString(),
  };
}

router.get(
  "/projects/:projectId/providers/:providerId/smtp",
  requirePermission("manage:tp-smtp", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const providerId = BigInt(req.params.providerId);
    const scope = await resolveScope(projectId, req.auth!.userId);
    if (scope.providerId && scope.providerId !== providerId) return void res.status(403).json({ error: "TP users can only manage their own SMTP." });
    const items = await prisma.tpSmtpConfiguration.findMany({
      where: { projectId, trainingProviderId: providerId },
      orderBy: { id: "desc" },
    });
    res.json({ items: items.map(serializeTpSmtp) });
  }
);

router.post(
  "/projects/:projectId/providers/:providerId/smtp",
  requirePermission("manage:tp-smtp", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const providerId = BigInt(req.params.providerId);
    const scope = await resolveScope(projectId, req.auth!.userId);
    if (scope.providerId && scope.providerId !== providerId) return void res.status(403).json({ error: "TP users can only manage their own SMTP." });
    const schema = z.object({
      senderName: z.string().min(1).max(255),
      senderEmail: z.string().email().max(255),
      smtpHost: z.string().min(1).max(255),
      smtpPort: z.string().min(1).max(255),
      smtpUser: z.string().min(1).max(255),
      smtpPassword: z.string().min(1).max(255),
      smtpType: z.enum(["default", "tls", "ssl"]).default("default"),
      status: z.enum(["1", "0"]).default("1"),
    });
    const parsed = schema.safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    const created = await prisma.tpSmtpConfiguration.create({
      data: {
        ...parsed.data,
        projectId,
        trainingProviderId: providerId,
      },
    });
    if (created.status === "1") {
      await prisma.tpSmtpConfiguration.updateMany({
        where: { projectId, trainingProviderId: providerId, id: { not: created.id } },
        data: { status: "0" },
      });
    }
    res.status(201).json({ item: serializeTpSmtp(created) });
  }
);

router.put(
  "/projects/:projectId/providers/:providerId/smtp/:smtpId",
  requirePermission("manage:tp-smtp", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const providerId = BigInt(req.params.providerId);
    const smtpId = BigInt(req.params.smtpId);
    const scope = await resolveScope(projectId, req.auth!.userId);
    if (scope.providerId && scope.providerId !== providerId) return void res.status(403).json({ error: "TP users can only manage their own SMTP." });
    const schema = z.object({
      senderName: z.string().min(1).max(255),
      senderEmail: z.string().email().max(255),
      smtpHost: z.string().min(1).max(255),
      smtpPort: z.string().min(1).max(255),
      smtpUser: z.string().min(1).max(255),
      smtpPassword: z.string().max(255).optional(),
      smtpType: z.enum(["default", "tls", "ssl"]).default("default"),
      status: z.enum(["1", "0"]).default("1"),
    });
    const parsed = schema.safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });

    const existing = await prisma.tpSmtpConfiguration.findFirst({
      where: { id: smtpId, projectId, trainingProviderId: providerId },
    });
    if (!existing) return void res.status(404).json({ error: "SMTP configuration not found." });
    const nextData: typeof parsed.data & { smtpPassword?: string } = { ...parsed.data };
    if (nextData.smtpPassword === undefined || nextData.smtpPassword.trim() === "") delete nextData.smtpPassword;

    const updated = await prisma.tpSmtpConfiguration.update({ where: { id: smtpId }, data: nextData });
    if (updated.status === "1") {
      await prisma.tpSmtpConfiguration.updateMany({
        where: { projectId, trainingProviderId: providerId, id: { not: updated.id } },
        data: { status: "0" },
      });
    }
    res.json({ item: serializeTpSmtp(updated) });
  }
);

router.delete(
  "/projects/:projectId/providers/:providerId/smtp/:smtpId",
  requirePermission("manage:tp-smtp", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const providerId = BigInt(req.params.providerId);
    const smtpId = BigInt(req.params.smtpId);
    const scope = await resolveScope(projectId, req.auth!.userId);
    if (scope.providerId && scope.providerId !== providerId) return void res.status(403).json({ error: "TP users can only manage their own SMTP." });
    await prisma.tpSmtpConfiguration.deleteMany({ where: { id: smtpId, projectId, trainingProviderId: providerId } });
    res.json({ ok: true });
  }
);

router.post(
  "/projects/:projectId/providers/:providerId/smtp/test",
  requirePermission("manage:tp-smtp", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const providerId = BigInt(req.params.providerId);
    const scope = await resolveScope(projectId, req.auth!.userId);
    if (scope.providerId && scope.providerId !== providerId) return void res.status(403).json({ error: "TP users can only manage their own SMTP." });
    const parsed = z
      .object({
        to: emailField,
        subject: textField({ label: "Subject", min: 1, max: 255 }),
        body: textField({ label: "Message", min: 1, max: 5000, multiline: true }),
      })
      .safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    const active = await prisma.tpSmtpConfiguration.findFirst({
      where: { projectId, trainingProviderId: providerId, status: "1" },
      orderBy: { id: "desc" },
    });
    if (!active) return void res.status(422).json({ error: "No active TP SMTP configuration." });
    try {
      const transport = createTransportFromConfig(active);
      const content = buildGenericNoticeEmailContent({
        subject: parsed.data.subject,
        message: parsed.data.body,
      });
      await transport.sendMail({
        from: `"${active.senderName}" <${active.senderEmail}>`,
        to: parsed.data.to,
        subject: parsed.data.subject,
        text: content.text,
        html: content.html,
      });
      res.json({ ok: true });
    } catch (e) {
      res.status(422).json({ error: smtpErrorMessage(e) });
    }
  }
);

export default router;
