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

/**
 * POST /api/me/signin
 * 用户每日签到 · 记录连续签到天数。
 * 已取消每日票数额度概念，签到不再向票数余额发放奖励。
 */
export async function POST() {
  try {
    const user = await getCurrentUser();
    if (!user) return ERR.UNAUTHORIZED();

    const today = startOfDay();
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);

    // 已签到则直接返回
    const existing = await prisma.signIn.findUnique({
      where: { userId_date: { userId: user.id, date: today } },
    });
    if (existing) {
      return ok(
        sanitizeBigInt({
          alreadySigned: true,
          streak: existing.streak,
        }),
      );
    }

    // 查询昨日签到判断连签
    const yest = await prisma.signIn.findUnique({
      where: { userId_date: { userId: user.id, date: yesterday } },
    });
    const streak = yest ? yest.streak + 1 : 1;

    const result = await prisma.signIn.create({
      data: {
        userId: user.id,
        date: today,
        streak,
        bonusVotes: 0, // 保留字段，但不再发放
      },
    });

    return ok(
      sanitizeBigInt({
        alreadySigned: false,
        streak: result.streak,
      }),
    );
  } catch (e) {
    console.error("[POST /api/me/signin]", e);
    return ERR.INTERNAL();
  }
}

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