import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireRole } from "@/lib/auth";
import { getUploadPolicy } from "@/lib/upload-policy";

const MAX_FILES = 5;

/** The institution's own support tickets with reply/attachment counts + last activity. */
export async function GET() {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const tickets = await prisma.supportTicket.findMany({
    where: { institutionId: session.institutionId },
    orderBy: [{ updatedAt: "desc" }, { id: "desc" }],
    include: {
      _count: { select: { messages: true, attachments: true } },
      messages: { orderBy: { createdAt: "desc" }, take: 1, select: { senderRole: true, createdAt: true } },
    },
  });

  return NextResponse.json({
    tickets: tickets.map(({ messages, _count, ...t }) => ({
      ...t,
      replyCount: _count.messages,
      attachmentCount: _count.attachments,
      lastReplyBy: messages[0]?.senderRole ?? null,
      lastActivityAt: messages[0]?.createdAt ?? t.createdAt,
    })),
  });
}

/** Create a ticket: { subject, message, attachments?: [{ fileName, mimeType, fileSize, data }] }. */
export async function POST(req: Request) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const body = await req.json();
    const subject = String(body.subject ?? "").trim();
    const message = String(body.message ?? "").trim();
    const rawFiles: unknown[] = Array.isArray(body.attachments) ? body.attachments : [];

    if (!subject || !message) {
      return NextResponse.json({ error: "Missing fields" }, { status: 400 });
    }
    if (rawFiles.length > MAX_FILES) {
      return NextResponse.json({ error: "TOO_MANY_FILES" }, { status: 400 });
    }
    const attachments = rawFiles.map((raw) => {
      const f = (raw ?? {}) as { fileName?: unknown; mimeType?: unknown; fileSize?: unknown; data?: unknown };
      return {
        fileName: String(f.fileName ?? "file").slice(0, 190),
        mimeType: String(f.mimeType ?? "application/octet-stream").slice(0, 100),
        fileSize: Number(f.fileSize) || 0,
        data: String(f.data ?? ""),
      };
    });
    const policy = await getUploadPolicy();
    const maxBase64 = Math.round(policy.docMaxKb * 1024 * 1.4) + 128; // ≈ base64 overhead
    if (attachments.some((f) => f.data.length > maxBase64 || !f.data)) {
      return NextResponse.json({ error: "FILE_TOO_LARGE" }, { status: 400 });
    }

    const ticket = await prisma.supportTicket.create({
      data: {
        institutionId: session.institutionId,
        subject,
        message,
        attachments: { create: attachments },
      },
      include: { _count: { select: { messages: true, attachments: true } } },
    });
    return NextResponse.json({ ticket });
  } catch {
    return NextResponse.json({ error: "Could not create ticket" }, { status: 500 });
  }
}
