export const dynamic = "force-dynamic";
import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";
import { getUserIdFromRequest } from "@/lib/auth";

export async function GET(req: Request) {
  const userId = getUserIdFromRequest(req);
  if (!userId) return NextResponse.json({ today: null, count: 0, days: [] });
  const url = new URL(req.url);
  const year = url.searchParams.get("year");
  const month = url.searchParams.get("month"); // 1-12
  const start = new Date(); start.setHours(0,0,0,0);
  const end = new Date(); end.setHours(23,59,59,999);
  const today = await prisma.attendance.findFirst({
    where: { userId, date: { gte: start, lte: end } },
  });
  const count = await prisma.attendance.count({ where: { userId } });
  // 월별 출석 일자 목록
  if (year && month) {
    const y = parseInt(year, 10);
    const m = parseInt(month, 10);
    if (!isNaN(y) && !isNaN(m) && m >= 1 && m <= 12) {
      const firstDay = new Date(Date.UTC(y, m - 1, 1, 0, 0, 0, 0));
      const lastDay = new Date(Date.UTC(y, m, 0, 23, 59, 59, 999));
      const records = await prisma.attendance.findMany({
        where: { userId, date: { gte: firstDay, lte: lastDay } },
        select: { date: true },
        orderBy: { date: "asc" },
      });
      const days = records.map(r => {
        const d = new Date(r.date);
        const yy = d.getUTCFullYear();
        const mm = String(d.getUTCMonth() + 1).padStart(2, "0");
        const dd = String(d.getUTCDate()).padStart(2, "0");
        return `${yy}-${mm}-${dd}`;
      });
      return NextResponse.json({ today: !!today, count, days });
    }
  }
  return NextResponse.json({ today: !!today, count });
}

export async function POST(req: Request) {
  const userId = getUserIdFromRequest(req);
  if (!userId) return NextResponse.json({ error: "login required" }, { status: 401 });
  const start = new Date(); start.setHours(0,0,0,0);
  const end = new Date(); end.setHours(23,59,59,999);
  const exists = await prisma.attendance.findFirst({ where: { userId, date: { gte: start, lte: end } } });
  if (exists) return NextResponse.json({ ok: true, duplicated: true });
  // normalize to UTC midnight
  const now = new Date();
  const normalized = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0));
  await prisma.attendance.create({ data: { userId, date: normalized } });
  return NextResponse.json({ ok: true });
}


