"use server";

import { headers } from "next/headers";
import {
  CarbonCalculationResult,
  CarbonCalculatorService,
} from "@/services/carbon-calculator.service";
import { CarbonUrlService } from "@/services/carbon-url.service";
import { RateLimiterService } from "@/services/rate-limiter.service";

const carbonUrlService = new CarbonUrlService();
const carbonCalculatorService = new CarbonCalculatorService();
const carbonRateLimiter = new RateLimiterService({
  limit: 6,
  windowMs: 60 * 1000,
});

const getClientIp = async (): Promise<string> => {
  const requestHeaders = await headers();
  const forwardedFor = requestHeaders.get("x-forwarded-for");
  const realIp = requestHeaders.get("x-real-ip");

  if (forwardedFor) {
    return forwardedFor.split(",")[0].trim();
  }

  if (realIp) {
    return realIp.trim();
  }

  return "unknown";
};

export const checkCarbonAction = async (
  url: string,
): Promise<CarbonCalculationResult> => {
  const clientIp = await getClientIp();
  const rateLimit = carbonRateLimiter.check(clientIp);

  if (!rateLimit.allowed) {
    return {
      ok: false,
      checkedUrl: "",
      error: `Too many requests. Please wait ${rateLimit.retryAfterSeconds} seconds and try again.`,
    };
  }

  const validationResult = carbonUrlService.validateAndNormalize(url || "");

  if (!validationResult.ok) {
    return {
      ok: false,
      checkedUrl: "",
      error: validationResult.error,
    };
  }

  return carbonCalculatorService.estimatePageCarbon(validationResult.normalizedUrl);
};
