import { prisma } from "@/lib/prisma";
import { getCurrentUser } from "@/lib/current-user";
import { ok, ERR, sanitizeBigInt } from "@/lib/api-response";

/**
 * GET /api/me
 * 当前用户信息：基础资料、累计投票数、应援列表、签到状态、今日票数额度。
 */
export async function GET() {
  try {
    const user = await getCurrentUser();
    if (!user) return ERR.UNAUTHORIZED();

    const today = startOfDay();

    type SupportRow = Awaited<
      ReturnType<typeof prisma.fanSupport.findMany>
    >[number] & {
      artist: {
        id: string;
        no: string;
        name: string;
        enName: string;
        voteCount: number;
        currentRank: number | null;
      };
    };

    const [profile, signIn, supports, dailyQuotaRow, config] =
      (await Promise.all([
        prisma.user.findUnique({
          where: { id: user.id },
          select: {
            id: true,
            nickname: true,
            avatar: true,
            phone: true,
            createdAt: true,
          },
        }),
        prisma.signIn.findFirst({
          where: { userId: user.id },
          orderBy: { date: "desc" },
        }),
        prisma.fanSupport.findMany({
          where: { userId: user.id },
          include: {
            artist: {
              select: {
                id: true,
                no: true,
                name: true,
                enName: true,
                voteCount: true,
                currentRank: true,
              },
            },
          },
          orderBy: { votedTotal: "desc" },
        }),
        prisma.dailyQuota.findUnique({
          where: { userId_date: { userId: user.id, date: today } },
        }),
        prisma.activityConfig.findUnique({ where: { id: 1 } }),
      ])) as [
        Awaited<ReturnType<typeof prisma.user.findUnique>>,
        Awaited<ReturnType<typeof prisma.signIn.findFirst>>,
        SupportRow[],
        Awaited<ReturnType<typeof prisma.dailyQuota.findUnique>>,
        Awaited<ReturnType<typeof prisma.activityConfig.findUnique>>,
      ];

    if (!profile) return ERR.NOT_FOUND("用户不存在");

    const totalVotes = await prisma.vote.aggregate({
      where: { userId: user.id },
      _sum: { count: true },
    });

    const dailyQuota = dailyQuotaRow?.totalQuota ?? config?.dailyQuota ?? 10;
    const usedToday = dailyQuotaRow?.usedQuota ?? 0;

    return ok(
      sanitizeBigInt({
        profile,
        signIn: {
          streak: signIn?.streak ?? 0,
          lastDate: signIn?.date ?? null,
          todaySignedIn: signIn ? sameDay(signIn.date, today) : false,
        },
        totalVotes: totalVotes._sum.count ?? 0,
        dailyQuota: {
          total: dailyQuota,
          used: usedToday,
          remaining: Math.max(0, dailyQuota - usedToday),
        },
        supports: supports.map((s: SupportRow) => ({
          artist: s.artist,
          votedTotal: s.votedTotal,
        })),
      }),
    );
  } catch (e) {
    console.error("[GET /api/me]", e);
    return ERR.INTERNAL();
  }
}

function startOfDay(d = new Date()): Date {
  const x = new Date(d);
  x.setHours(0, 0, 0, 0);
  return x;
}

function sameDay(a: Date, b: Date) {
  return (
    a.getFullYear() === b.getFullYear() &&
    a.getMonth() === b.getMonth() &&
    a.getDate() === b.getDate()
  );
}
