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

/**
 * 终身投票总额度,与前端 src/lib/store.ts 的 TOTAL_VOTE_QUOTA 对齐。
 */
const TOTAL_VOTE_QUOTA = 12;

/**
 * GET /api/me
 * 当前用户信息:基础资料、应援列表、签到状态、终身票数额度。
 *
 * 新增字段 votedArtists: string[] —— 按投票时间升序(最早投的在前),
 * 供前端 hydrate 时取代纯 localStorage,跨设备/清缓存后仍可恢复。
 */
export async function GET() {
  try {
    const user = await getCurrentUser();
    if (!user) return ERR.UNAUTHORIZED();

    const today = startOfUtcDay();

    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, votedList] = (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: { createdAt: "asc" },
      }),
      // 按投票顺序拉 votedArtists —— 前端 store 用作 hydrate 真相源
      prisma.vote.findMany({
        where: { userId: user.id },
        select: { artistId: true, createdAt: true },
        orderBy: { createdAt: "asc" },
      }),
    ])) as [
      Awaited<ReturnType<typeof prisma.user.findUnique>>,
      Awaited<ReturnType<typeof prisma.signIn.findFirst>>,
      SupportRow[],
      { artistId: string; createdAt: Date }[],
    ];

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

    const votedArtists = votedList.map((v) => v.artistId);
    const votedCount = votedArtists.length;
    const remaining = Math.max(0, TOTAL_VOTE_QUOTA - votedCount);

    return ok(
      sanitizeBigInt({
        profile,
        signIn: {
          streak: signIn?.streak ?? 0,
          lastDate: signIn?.date ?? null,
          todaySignedIn: signIn ? isSameUtcDay(signIn.date, today) : false,
        },
        // 终身票数视图 —— 替代旧的 dailyQuota
        voteQuota: {
          total: TOTAL_VOTE_QUOTA,
          used: votedCount,
          remaining,
        },
        // 已投艺人 ID 列表(按时间升序),前端 hydrate 时回放到 store
        votedArtists,
        supports: supports.map((s: SupportRow) => ({
          artist: s.artist,
          // 新规则下 votedTotal 固定 1;旧数据 votedTotal>1 仍真实反映历史
          votedTotal: s.votedTotal,
        })),
      }),
    );
  } catch (e) {
    console.error("[GET /api/me]", e);
    return ERR.INTERNAL();
  }
}
