import { prisma } from '../../models';

/**
 * 签到服务
 */

// 检查今日是否已签到
export async function getSignStatus(userId: number) {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const tomorrow = new Date(today);
  tomorrow.setDate(tomorrow.getDate() + 1);

  // 查找今天的签到记录
  const todaySign = await prisma.signRecord.findFirst({
    where: {
      userId,
      createdAt: {
        gte: today,
        lt: tomorrow,
      },
    },
  });

  // 计算连续签到天数
  let consecutiveDays = 0;
  if (todaySign) {
    // 今天是签到日，从今天往前计算连续天数
    let checkDate = new Date(today);
    while (true) {
      const startOfDay = new Date(checkDate);
      startOfDay.setHours(0, 0, 0, 0);
      const endOfDay = new Date(checkDate);
      endOfDay.setHours(23, 59, 59, 999);

      const record = await prisma.signRecord.findFirst({
        where: {
          userId,
          createdAt: {
            gte: startOfDay,
            lte: endOfDay,
          },
        },
      });

      if (record) {
        consecutiveDays++;
        checkDate.setDate(checkDate.getDate() - 1);
      } else {
        break;
      }
    }
  } else {
    // 今天没签到，检查昨天是否签到来确定连续天数
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);
    const yStart = new Date(yesterday);
    yStart.setHours(0, 0, 0, 0);
    const yEnd = new Date(yesterday);
    yEnd.setHours(23, 59, 59, 999);

    const yesterdaySign = await prisma.signRecord.findFirst({
      where: {
        userId,
        createdAt: {
          gte: yStart,
          lte: yEnd,
        },
      },
    });

    if (yesterdaySign) {
      // 从昨天开始计算连续天数
      let checkDate = new Date(yesterday);
      while (true) {
        const startOfDay = new Date(checkDate);
        startOfDay.setHours(0, 0, 0, 0);
        const endOfDay = new Date(checkDate);
        endOfDay.setHours(23, 59, 59, 999);

        const record = await prisma.signRecord.findFirst({
          where: {
            userId,
            createdAt: {
              gte: startOfDay,
              lte: endOfDay,
            },
          },
        });

        if (record) {
          consecutiveDays++;
          checkDate.setDate(checkDate.getDate() - 1);
        } else {
          break;
        }
      }
    }
  }

  return {
    signed: !!todaySign,
    consecutiveDays,
    lastSignDate: todaySign?.createdAt || null,
  };
}

// 执行签到
export async function signIn(userId: number) {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const tomorrow = new Date(today);
  tomorrow.setDate(tomorrow.getDate() + 1);

  // 检查今天是否已签到
  const existingSign = await prisma.signRecord.findFirst({
    where: {
      userId,
      createdAt: {
        gte: today,
        lt: tomorrow,
      },
    },
  });

  if (existingSign) {
    throw new Error('今日已签到');
  }

  // 创建签到记录
  const signRecord = await prisma.signRecord.create({
    data: {
      userId,
    },
  });

  // 增加用户免费次数（每日首次签到给3次）
  const bonusCount = 3;

  // 更新用户每日使用次数
  const user = await prisma.user.findUnique({ where: { id: userId } });
  if (user) {
    await prisma.user.update({
      where: { id: userId },
      data: {
        dailyUsage: Math.max(0, user.dailyUsage - bonusCount),
        lastUsageDate: new Date().toISOString().split('T')[0],
      },
    });
  }

  // 获取签到状态
  const status = await getSignStatus(userId);

  return {
    ...status,
    bonusCount,
  };
}
