import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";
import { z } from "zod";
import { getUserIdFromRequest } from "@/lib/auth";

const sendSchema = z.object({
  receiverId: z.string().min(1, "수신자 정보가 없습니다"),
  body: z.string().min(1, "메시지를 입력하세요").max(2000, "메시지는 2000자 이하여야 합니다"),
});

export async function POST(req: Request) {
  const senderId = getUserIdFromRequest(req);
  if (!senderId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const contentType = req.headers.get("content-type") || "";
  let data: any = {};
  if (contentType.includes("application/json")) {
    data = await req.json().catch(() => ({}));
  } else if (contentType.includes("application/x-www-form-urlencoded")) {
    const form = await req.formData();
    data = Object.fromEntries(form.entries());
  } else {
    // 기본적으로 form 으로 간주
    const form = await req.formData().catch(() => null);
    if (form) data = Object.fromEntries(form.entries());
  }
  const parsed = sendSchema.safeParse(data);
  if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
  const { receiverId, body } = parsed.data;
  if (receiverId === senderId) {
    return NextResponse.json({ error: "자기 자신에게는 보낼 수 없습니다" }, { status: 400 });
  }
  const receiver = await prisma.user.findUnique({ where: { userId: receiverId }, select: { userId: true } });
  if (!receiver) return NextResponse.json({ error: "수신자를 찾을 수 없습니다" }, { status: 404 });
  const message = await prisma.message.create({
    data: { senderId, receiverId, body },
    select: { id: true, senderId: true, receiverId: true, body: true, createdAt: true },
  });
  return NextResponse.json({ message }, { status: 201 });
}

const listQuery = z.object({
  box: z.enum(["received", "sent"]).default("received").optional(),
  page: z.coerce.number().min(1).default(1).optional(),
  pageSize: z.coerce.number().min(1).max(100).default(20).optional(),
});

export async function GET(req: Request) {
  const userId = getUserIdFromRequest(req);
  if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const { searchParams } = new URL(req.url);
  const parsed = listQuery.safeParse(Object.fromEntries(searchParams));
  if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
  const { box = "received", page = 1, pageSize = 20 } = parsed.data;
  const where =
    box === "received"
      ? { receiverId: userId }
      : { senderId: userId };
  const [total, items] = await Promise.all([
    prisma.message.count({ where }),
    prisma.message.findMany({
      where,
      orderBy: { createdAt: "desc" },
      skip: (page - 1) * pageSize,
      take: pageSize,
      select: {
        id: true,
        body: true,
        createdAt: true,
        sender: { select: { userId: true, nickname: true } },
        receiver: { select: { userId: true, nickname: true } },
      },
    }),
  ]);
  return NextResponse.json({ total, page, pageSize, items });
}


