import { NextRequest, NextResponse } from "next/server";

const BASE_URL = process.env.BASE_URL;
async function fetchContacts({
    kSession,
    kSessionId,
    headerXAccount,
    headerXContact
}: {
    kSession: string;
    kSessionId: string;
    headerXAccount: string;
    headerXContact: string
}) {
    const url = `${BASE_URL}/v1/member/account/contacts`;
    const res = await fetch(url, {
        method: "GET",
        headers: {
            "x-account": headerXAccount,
            "x-contact": headerXContact,
            Cookie: `k_session=${kSession}; k_session_id=${kSessionId}`,
        },
        cache: "no-store",
    });
    const text = await res.text();
    return { res, text };

}

export async function GET(req: NextRequest) {
    try {
        const headerKSession = req.headers.get("x-k-session") || "";
        const headerKSessionId = req.headers.get("x-k-session-id") || "";
        const headerXAccount = req.headers.get("x-account") || "";
        const headerXContact = req.headers.get("x-contact") || "";

        const cookieKSession = req.cookies.get("k_session")?.value || "";
        const cookieKSessionId = req.cookies.get("k_session_id")?.value || "";

        let kSession = headerKSession || cookieKSession;
        let kSessionId = headerKSessionId || cookieKSessionId;

        if (!kSession || !kSessionId) {
            return NextResponse.json(
                { error: true, message: "Missing session" },
                { status: 401 }
            );
        }

        let { res, text } = await fetchContacts({ kSession, kSessionId, headerXAccount, headerXContact });
        const isSessionExpired = res.status === 401 || res.status === 419 || text.includes("expired");

        if (!res.ok) {
            return NextResponse.json(
                { error: true, message: text },
                { status: res.status }
            );
        }

        const json = JSON.parse(text);
        const owner = json.data.owners?.[0];

        const responseBody: any = {
            data: {
                first_name: owner?.first_name,
                email: owner?.email,
            },
            session: {
                k_session: kSession,
                k_session_id: kSessionId,
            },
        };

        const response = NextResponse.json(responseBody, { status: 200 });

        response.cookies.set("k_session", kSession, {
            httpOnly: false,
            path: "/",
            sameSite: "lax",
        });
        response.cookies.set("k_session_id", kSessionId, {
            httpOnly: false,
            path: "/",
            sameSite: "lax",
        });

        return response;
    } catch (err: any) {
        return NextResponse.json(
            { error: true, message: err.message || "Internal server error" },
            { status: 500 }
        );
    }
}

