import { Response, NextFunction } from "express"
import { prisma, checkAndResetSubscriptionPeriod, SUBSCRIPTION_PLANS } from "@codeflash-ai/common"
import { AuthorizedUserReq } from "../types.js"
import { logger } from "../utils/logger.js"
import { missingUserId, subscriptionInactive, internalServerError } from "../exceptions/index.js"

export async function trackUsage(req: AuthorizedUserReq, res: Response, next: NextFunction) {
  const userId = req.userId

  if (!userId) {
    // Log missing userId - logger handles environment filtering automatically
    // Production: WARN level (important business logic issue), Development: WARN level (important business logic issue)
    logger.warn("Track usage called without userId", {
      requestId: req.requestId,
      traceId: req.traceId,
      endpoint: req.path,
      operation: "usage_tracking",
    })

    next(missingUserId({ requestId: req.requestId, endpoint: req.path }))
    return
  }

  try {
    // Log usage tracking start - logger handles environment filtering automatically
    // Production: Not logged (DEBUG level), Development: Full details (DEBUG level)
    logger.debug("Starting usage tracking", {
      requestId: req.requestId,
      traceId: req.traceId,
      endpoint: req.path,
      operation: "usage_tracking",
      userId,
    })

    // Get subscription info for the user
    const subscription = await prisma.subscriptions.findUnique({
      where: { user_id: userId },
    })

    if (!subscription) {
      // Log creating new subscription - logger handles environment filtering automatically
      // Production: INFO level (important business event), Development: INFO level (important business event)
      logger.info("Creating new free tier subscription", {
        requestId: req.requestId,
        traceId: req.traceId,
        endpoint: req.path,
        operation: "usage_tracking",
        userId,
      })

      // Create free tier subscription if none exists
      const newSubscription = await prisma.subscriptions.create({
        data: {
          user_id: userId,
          plan_type: "free",
          optimizations_limit: SUBSCRIPTION_PLANS.FREE.optimizations,
          subscription_status: "active",
          optimizations_used: 0,
        },
      })

      // Add subscription info to request for later use
      req.subscriptionInfo = {
        userId,
        tier: String(newSubscription.plan_type),
        used: Number(newSubscription.optimizations_used),
        limit: Number(newSubscription.optimizations_limit),
      }

      // Log subscription creation success - logger handles environment filtering automatically
      // Production: INFO level (important business event), Development: INFO level (important business event)
      logger.info("Free tier subscription created successfully", {
        requestId: req.requestId,
        traceId: req.traceId,
        endpoint: req.path,
        operation: "usage_tracking",
        userId,
        tier: newSubscription.plan_type,
        limit: newSubscription.optimizations_limit,
      })

      next()
      return
    }

    // Check subscription status and limits
    if (subscription.subscription_status !== "active") {
      // Log inactive subscription - logger handles environment filtering automatically
      // Production: WARN level (important business logic issue), Development: WARN level (important business logic issue)
      logger.warn("Subscription is not active", {
        requestId: req.requestId,
        traceId: req.traceId,
        endpoint: req.path,
        operation: "usage_tracking",
        userId,
        status: subscription.subscription_status,
      })

      next(subscriptionInactive({ requestId: req.requestId, userId, endpoint: req.path }))
      return
    }

    // Check if we need to reset monthly usage (lazy reset)
    const currentSubscription = await checkAndResetSubscriptionPeriod(userId)
    const currentOptimizationsUsed = currentSubscription?.optimizations_used || 0

    // Add subscription info to request for later use
    req.subscriptionInfo = {
      userId,
      tier: String(subscription.plan_type),
      used: currentOptimizationsUsed,
      limit: Number(subscription.optimizations_limit),
    }

    // Log usage tracking completion - logger handles environment filtering automatically
    // Production: Not logged (DEBUG level), Development: Full details (DEBUG level)
    logger.debug("Usage tracking completed successfully", {
      requestId: req.requestId,
      traceId: req.traceId,
      endpoint: req.path,
      operation: "usage_tracking",
      userId,
      tier: subscription.plan_type,
      used: currentOptimizationsUsed,
      limit: subscription.optimizations_limit,
    })

    next()
  } catch (error) {
    // Log usage tracking error - logger handles environment filtering automatically
    // Production: ERROR level (critical infrastructure issue), Development: ERROR level (critical infrastructure issue)
    logger.errorWithSentry(
      "Error tracking usage",
      {
        requestId: req.requestId,
        traceId: req.traceId,
        endpoint: req.path,
        operation: "usage_tracking",
        userId,
      },
      {},
      error as Error,
    )

    next(
      internalServerError("Error tracking usage", {
        requestId: req.requestId,
        userId,
        endpoint: req.path,
      }),
    )
  }
}
