import { prisma } from "@/lib/prisma";
import { getAdminUser } from "@/lib/auth";
import { NextResponse } from "next/server";

const UPLOAD_ENDPOINT = "http://167.71.224.75:8501/upload";

const serializeBigInt = (data: any) =>
  JSON.parse(
    JSON.stringify(data, (_, value) =>
      typeof value === "bigint"
        ? value.toString()
        : value
    )
  );

async function uploadToExternalServer(
  file: File,
  folder: string = "why-rkda"
): Promise<string> {
  const formData = new FormData();

  formData.append("folder", folder);
  formData.append("file", file);

  const response = await fetch(UPLOAD_ENDPOINT, {
    method: "POST",
    body: formData,
    cache: "no-store",
  });

  if (!response.ok) {
    throw new Error("File upload failed");
  }

  const result = await response.json();

  if (!result.success || !result.url) {
    throw new Error(result.message || "Upload failed");
  }

  return result.url;
}

export async function GET() {
  const admin = await getAdminUser();

  if (!admin) {
    return NextResponse.json(
      {
        success: false,
        message: "Unauthorized",
      },
      {
        status: 401,
      }
    );
  }

  try {
    const data = await prisma.cms_why_rkda.findMany({
      orderBy: {
        sort_order: "asc",
      },
    });

    return NextResponse.json({
      success: true,
      data: serializeBigInt(data),
    });


  } catch (error: any) {
    return NextResponse.json(
      {
        success: false,
        message: error.message || "Failed to fetch data",
      },
      {
        status: 500,
      }
    );
  }
}

export async function POST(req: Request) {
  const admin = await getAdminUser();

  if (!admin) {
    return NextResponse.json(
      {
        success: false,
        message: "Unauthorized",
      },
      {
        status: 401,
      }
    );
  }

  try {
    const formData = await req.formData();

    let icon = "";

    const iconFile = formData.get("icon");

    if (
      iconFile &&
      iconFile instanceof File &&
      iconFile.size > 0
    ) {
      icon = await uploadToExternalServer(
        iconFile,
        "why-rkda"
      );
    }

    const item = await prisma.cms_why_rkda.create({
      data: {
        title: String(formData.get("title") || ""),
        description: String(
          formData.get("description") || ""
        ),
        icon,
        sort_order: Number(
          formData.get("sort_order") || 0
        ),
        status:
          String(formData.get("status")) === "true",
      },
    });

    return NextResponse.json({
      success: true,
      data: serializeBigInt(item),
    });

  } catch (error: any) {
    return NextResponse.json(
      {
        success: false,
        message: error.message || "Failed to create record",
      },
      {
        status: 500,
      }
    );
  }
}

export async function PUT(req: Request) {
  const admin = await getAdminUser();

  if (!admin) {
    return NextResponse.json(
      {
        success: false,
        message: "Unauthorized",
      },
      {
        status: 401,
      }
    );
  }

  try {
    const formData = await req.formData();

    const id = BigInt(
      String(formData.get("id"))
    );

    const existing =
      await prisma.cms_why_rkda.findUnique({
        where: {
          id,
        },
      });

    if (!existing) {
      return NextResponse.json(
        {
          success: false,
          message: "Record not found",
        },
        {
          status: 404,
        }
      );
    }

    let icon = existing.icon;

    const iconFile = formData.get("icon");

    if (
      iconFile &&
      iconFile instanceof File &&
      iconFile.size > 0
    ) {
      icon = await uploadToExternalServer(
        iconFile,
        "why-rkda"
      );
    }

    const item =
      await prisma.cms_why_rkda.update({
        where: {
          id,
        },
        data: {
          title: String(
            formData.get("title") || ""
          ),
          description: String(
            formData.get("description") || ""
          ),
          icon,
          sort_order: Number(
            formData.get("sort_order") || 0
          ),
          status:
            String(formData.get("status")) ===
            "true",
          updated_at: new Date(),
        },
      });

    return NextResponse.json({
      success: true,
      data: serializeBigInt(item),
    });
  } catch (error: any) {
    return NextResponse.json(
      {
        success: false,
        message: error.message || "Failed to update record",
      },
      {
        status: 500,
      }
    );
  }
}

export async function DELETE(req: Request) {
  const admin = await getAdminUser();

  if (!admin) {
    return NextResponse.json(
      {
        success: false,
        message: "Unauthorized",
      },
      {
        status: 401,
      }
    );
  }

  try {
    const { searchParams } = new URL(req.url);

    const id = BigInt(
      searchParams.get("id") || "0"
    );

    await prisma.cms_why_rkda.delete({
      where: {
        id,
      },
    });

    return NextResponse.json({
      success: true,
      message: "Deleted successfully",
    });

  } catch (error: any) {
    return NextResponse.json(
      {
        success: false,
        message: error.message || "Failed to delete record",
      },
      {
        status: 500,
      }
    );
  }
}
