"use server";

import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { getCurrentCustomerId } from "@/lib/customer-auth";
import { requirePermission } from "@/lib/permissions";
import { isValidEmail } from "@/lib/customer-otp";
import { sendNewTicketNotification, sendTicketReplyEmail } from "@/lib/resend";

const VALID_STATUSES = ["open", "in_progress", "resolved", "closed"];

/** True if the current visitor (logged-in customer matching ticket.customerId, or matching email) owns this ticket. */
async function ownsTicket(ticket: { customerId: string | null; email: string }, emailParam?: string): Promise<boolean> {
  const sessionCustomerId = await getCurrentCustomerId();
  if (sessionCustomerId && ticket.customerId === sessionCustomerId) return true;
  if (emailParam && emailParam.trim().toLowerCase() === ticket.email.toLowerCase()) return true;
  return false;
}

export async function createTicket(formData: FormData) {
  const name = String(formData.get("name") ?? "").trim();
  const email = String(formData.get("email") ?? "").trim().toLowerCase();
  const subject = String(formData.get("subject") ?? "").trim();
  const body = String(formData.get("body") ?? "").trim();
  if (!name || !email || !subject || !body) {
    redirect(`/contact?error=Fill+in+your+name%2C+email%2C+subject%2C+and+message`);
  }
  if (!isValidEmail(email)) {
    redirect(`/contact?error=Enter+a+valid+email+address`);
  }
  if (name.length > 100 || subject.length > 150 || body.length > 5000) {
    redirect(`/contact?error=One+of+the+fields+is+too+long`);
  }

  const sessionCustomerId = await getCurrentCustomerId();
  const existingCustomer = sessionCustomerId
    ? null
    : await prisma.customer.findUnique({ where: { email } });
  const customerId = sessionCustomerId ?? existingCustomer?.id ?? null;

  const ticket = await prisma.supportTicket.create({
    data: { customerId, name, email, subject, messages: { create: [{ senderType: "customer", body }] } },
  });

  try {
    const settings = await prisma.notificationSettings.findFirst();
    if (settings?.notifyOnNewTicket && settings.notifyEmail) {
      await sendNewTicketNotification(settings.notifyEmail, { id: ticket.id, name, subject });
    }
  } catch {
    // non-fatal — the ticket exists regardless of whether the admin got notified
  }

  revalidatePath("/iv-manage-84x2/support");
  redirect(`/support/${ticket.id}?email=${encodeURIComponent(email)}&success=Ticket+created.`);
}

export async function replyAsCustomer(ticketId: string, emailParam: string | null, formData: FormData) {
  const ticket = await prisma.supportTicket.findUniqueOrThrow({ where: { id: ticketId } });
  const allowed = await ownsTicket(ticket, emailParam ?? undefined);
  if (!allowed) redirect("/track-order");

  const body = String(formData.get("body") ?? "").trim();
  if (!body) redirect(`/support/${ticketId}?email=${encodeURIComponent(emailParam ?? "")}&error=Write+a+message`);
  if (body.length > 5000) redirect(`/support/${ticketId}?email=${encodeURIComponent(emailParam ?? "")}&error=Message+is+too+long`);

  await prisma.$transaction([
    prisma.ticketMessage.create({ data: { ticketId, senderType: "customer", body } }),
    prisma.supportTicket.update({ where: { id: ticketId }, data: { status: "open" } }),
  ]);

  revalidatePath(`/support/${ticketId}`);
  revalidatePath("/iv-manage-84x2/support");
  redirect(`/support/${ticketId}?email=${encodeURIComponent(emailParam ?? "")}&success=Reply+sent.`);
}

export async function replyAsStaff(ticketId: string, formData: FormData) {
  await requirePermission("support", "edit");
  const body = String(formData.get("body") ?? "").trim();
  if (!body) redirect(`/iv-manage-84x2/support/${ticketId}?error=Write+a+message`);
  if (body.length > 5000) redirect(`/iv-manage-84x2/support/${ticketId}?error=Message+is+too+long`);

  const ticket = await prisma.$transaction(async (tx) => {
    await tx.ticketMessage.create({ data: { ticketId, senderType: "staff", body } });
    return tx.supportTicket.update({ where: { id: ticketId }, data: { status: "in_progress" } });
  });

  try {
    await sendTicketReplyEmail(ticket.email, { subject: ticket.subject, replyBody: body });
  } catch {
    // non-fatal — the reply is saved regardless of whether the email went out
  }

  revalidatePath(`/iv-manage-84x2/support/${ticketId}`);
  revalidatePath("/iv-manage-84x2/support");
  redirect(`/iv-manage-84x2/support/${ticketId}?success=Reply+sent.`);
}

export async function updateTicketStatus(ticketId: string, formData: FormData) {
  await requirePermission("support", "edit");
  const status = String(formData.get("status") ?? "");
  if (!VALID_STATUSES.includes(status)) redirect(`/iv-manage-84x2/support/${ticketId}?error=Invalid+status`);

  await prisma.supportTicket.update({ where: { id: ticketId }, data: { status } });
  revalidatePath(`/iv-manage-84x2/support/${ticketId}`);
  revalidatePath("/iv-manage-84x2/support");
  redirect(`/iv-manage-84x2/support/${ticketId}?success=Status+updated.`);
}
