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";
// Do NOT use https://quality-web-developer.com:8501/upload
// unless you have configured SSL on port 8501.

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

async function uploadToExternalServer(
    file: File,
    folder: string = "vision-mission"
): Promise<string> {
    try {
        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",
        });

        const responseText = await response.text();

        if (!response.ok) {
            throw new Error(`Upload failed (${response.status})`);
        }

        let result: {
            success: boolean;
            url?: string;
            error?: string;
            message?: string;
        };

        try {
            result = JSON.parse(responseText);
        } catch {
            throw new Error("Invalid JSON response from upload server");
        }

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

        if (!result.url) {
            throw new Error("Upload server did not return file URL");
        }

        return result.url;
    } catch (error) {
        console.error("External upload error:", error);
        throw error;
    }
}

// GET: fetch the single Vision & Mission entry for a page (defaults to 1 = home)
export async function GET(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 pageIdParam = searchParams.get("page_id");

        const page_id = pageIdParam ? BigInt(pageIdParam) : BigInt(1);

        const data = await prisma.cms_vision_mission.findUnique({
            where: { page_id },
        });

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

// POST: create the Vision & Mission entry for a page (only if one doesn't exist yet)
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();

        const page_id = formData.get("page_id")
            ? BigInt(String(formData.get("page_id")))
            : BigInt(1);

        const pageExists = await prisma.cms_pages.findUnique({
            where: { id: page_id },
        });

        if (!pageExists) {
            return NextResponse.json(
                { success: false, message: "Selected page does not exist" },
                { status: 400 }
            );
        }

        const existing = await prisma.cms_vision_mission.findUnique({
            where: { page_id },
        });

        if (existing) {
            return NextResponse.json(
                {
                    success: false,
                    message: "An entry already exists for this page. Please edit it instead.",
                },
                { status: 400 }
            );
        }

        const vision_description = String(formData.get("vision_description") || "").trim();
        const mission_description = String(formData.get("mission_description") || "").trim();

        if (!vision_description || !mission_description) {
            return NextResponse.json(
                { success: false, message: "Vision and Mission descriptions are required" },
                { status: 400 }
            );
        }

        let vision_image = "";
        let mission_image = "";

        const visionImageFile = formData.get("vision_image");
        const missionImageFile = formData.get("mission_image");

        if (
            visionImageFile &&
            visionImageFile instanceof File &&
            visionImageFile.size > 0
        ) {
            vision_image = await uploadToExternalServer(
                visionImageFile,
                "vision-mission"
            );
        }

        if (
            missionImageFile &&
            missionImageFile instanceof File &&
            missionImageFile.size > 0
        ) {
            mission_image = await uploadToExternalServer(
                missionImageFile,
                "vision-mission"
            );
        }

        const item = await prisma.cms_vision_mission.create({
            data: {
                page_id,
                title: String(formData.get("title") || "Our Vision & Mission").trim(),
                mission_image,
                vision_image,
                vision_title: String(formData.get("vision_title") || "Our Vision").trim(),
                vision_description,
                mission_title: String(formData.get("mission_title") || "Our Mission").trim(),
                mission_description,
                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 }
        );
    }
}

// PUT: update the existing Vision & Mission entry
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_vision_mission.findUnique({
            where: { id },
        });

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

        const vision_description = String(formData.get("vision_description") || "").trim();
        const mission_description = String(formData.get("mission_description") || "").trim();

        if (!vision_description || !mission_description) {
            return NextResponse.json(
                { success: false, message: "Vision and Mission descriptions are required" },
                { status: 400 }
            );
        }

        let vision_image = existing.vision_image;
        let mission_image = existing.mission_image;

        const visionImageFile = formData.get("vision_image");
        const missionImageFile = formData.get("mission_image");

        if (
            visionImageFile &&
            visionImageFile instanceof File &&
            visionImageFile.size > 0
        ) {
            vision_image = await uploadToExternalServer(
                visionImageFile,
                "vision-mission"
            );
        }

        if (
            missionImageFile &&
            missionImageFile instanceof File &&
            missionImageFile.size > 0
        ) {
            mission_image = await uploadToExternalServer(
                missionImageFile,
                "vision-mission"
            );
        }

        const item = await prisma.cms_vision_mission.update({
            where: { id },
            data: {
                title: String(formData.get("title") || "Our Vision & Mission").trim(),
                vision_image,
                mission_image,
                vision_title: String(formData.get("vision_title") || "Our Vision").trim(),
                vision_description,
                mission_title: String(formData.get("mission_title") || "Our Mission").trim(),
                mission_description,
                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 }
        );
    }
}