import { prisma } from "./prisma-client"

export async function checkAndResetSubscriptionPeriod(userId: string) {
  const subscription = await prisma.subscriptions.findUnique({
    where: { user_id: userId },
  })

  if (!subscription) {
    return null
  }
  if (subscription.plan_type === "free") {
    const now = new Date()
    const periodEnd = subscription.current_period_end

    if (periodEnd && now > periodEnd) {
      // Period has ended, reset usage and update period
      const { start, end } = getNextSubscriptionPeriod(subscription.current_period_end)

      const updatedSubscription = await prisma.subscriptions.update({
        where: { user_id: userId },
        data: {
          optimizations_used: 0,
          current_period_start: start,
          current_period_end: end,
        },
      })

      return updatedSubscription
    }
  }
  return subscription
}

// period-utils.ts
export function addMonthsSafe(date: Date, months: number) {
  const result = new Date(date)
  const day = result.getDate()

  result.setDate(1)
  result.setMonth(result.getMonth() + months)

  const lastDay = new Date(result.getFullYear(), result.getMonth() + 1, 0).getDate()
  result.setDate(Math.min(day, lastDay))

  return result
}

export function getNextSubscriptionPeriod(periodEnd: Date) {
  const start = addMonthsSafe(periodEnd, 1)
  const end = addMonthsSafe(start, 1)
  return { start, end }
}
