import { NextRequest, NextResponse } from "next/server";
import {API_BASE_URL} from "@/constants/index";
import path from "path";
import fs from "fs";


export async function GET(request: Request) {
    try{
    const url = new URL(request.url);
    const segments = url.pathname.split('/');
    const uuid = segments[segments.length - 1];
    const _url = API_BASE_URL+"mg-id/"+uuid;
    const apiRes = await fetch(_url);
    
    if (!apiRes.ok) {
      return new NextResponse("Image not found", { status: 404 });
    }

    const cardFromLaravel = await apiRes.text();

    const filename = "";
  
    
    const imagePath = path.join(process.cwd(), "public", "cards", cardFromLaravel);
    if (!fs.existsSync(imagePath)) {
      return NextResponse.json({ success: false, error: "Image file not found" }, { status: 404 });
    }

    const imageBuffer = fs.readFileSync(imagePath);
    const ext = path.extname(imagePath).toLowerCase();
    let contentType = "image/jpeg";
    if (ext === ".webp") contentType = "image/webp";
    else if (ext === ".png") contentType = "image/png";
    else if (ext === ".gif") contentType = "image/gif";

    return new NextResponse(imageBuffer, {
      status: 200,
      headers: { "Content-Type": contentType },
    });
  }catch {
    return NextResponse.json({ success: false, msg:"smeting is wrong" });
  }
}
