/* eslint-disable @typescript-eslint/no-explicit-any */
import { NextRequest, NextResponse } from "next/server";
import sharp from "sharp";

export const dynamic = "force-dynamic";
export const revalidate = 0;

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ name: string }> },
) {
  try {
    const { name } = await params;
    console.log("name", name);

    const searchParams = request.nextUrl.searchParams;
    const logoUrl = searchParams.get("url");
    const size = parseInt(searchParams.get("size") || "192");

    if (!logoUrl) {
      return new NextResponse("Logo URL is required", { status: 400 });
    }

    // دانلود تصویر
    const imageResponse = await fetch(logoUrl);
    if (!imageResponse.ok) {
      return new NextResponse("Failed to fetch logo", { status: 404 });
    }

    const imageBuffer = Buffer.from(await imageResponse.arrayBuffer());

    // دریافت ابعاد تصویر
    const metadata = await sharp(imageBuffer).metadata();
    const { width, height } = metadata;

    if (!width || !height) {
      return new NextResponse("Invalid image", { status: 400 });
    }

    // اگر تصویر از قبل مربع باشد، مستقیماً resize می‌کنیم
    if (width === height) {
      const processedImage = sharp(imageBuffer).resize(size, size, {
        fit: "contain",
        background: { r: 0, g: 0, b: 0, alpha: 0 },
      });
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const outputBuffer: any = await processedImage.png().toBuffer();

      return new NextResponse(outputBuffer, {
        headers: {
          "Content-Type": "image/png",
          "Cache-Control": "public, max-age=31536000, immutable",
        },
      });
    }

    // محاسبه نسبت برای resize اولیه (برای بهینه‌سازی)
    const maxDimension = Math.max(width, height);
    const scale = size / maxDimension;
    const newWidth = Math.round(width * scale);
    const newHeight = Math.round(height * scale);

    // ابتدا resize می‌کنیم و سپس padding اضافه می‌کنیم
    const paddingTop = Math.floor((size - newHeight) / 2);
    const paddingBottom = size - newHeight - paddingTop;
    const paddingLeft = Math.floor((size - newWidth) / 2);
    const paddingRight = size - newWidth - paddingLeft;

    const processedImage = sharp(imageBuffer)
      .resize(newWidth, newHeight, {
        fit: "contain",
        background: { r: 0, g: 0, b: 0, alpha: 0 },
      })
      .extend({
        top: paddingTop,
        bottom: paddingBottom,
        left: paddingLeft,
        right: paddingRight,
        background: { r: 0, g: 0, b: 0, alpha: 0 },
      });

    // تبدیل به PNG و برگرداندن
    const outputBuffer: any = await processedImage.png().toBuffer();

    return new NextResponse(outputBuffer, {
      headers: {
        "Content-Type": "image/png",
        "Cache-Control": "public, max-age=31536000, immutable",
      },
    });
  } catch (error) {
    console.error("Error processing logo:", error);
    return new NextResponse("Internal Server Error", { status: 500 });
  }
}
