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

const KUNDALI_MATCH_AGGREGATE_API =
    "https://api.astrology.togwe.com/api/user/matching/aggregate";

export async function POST(
    request: NextRequest
) {
    try {
        const authorization =
            request.headers.get(
                "authorization"
            );

        if (!authorization) {
            return NextResponse.json(
                {
                    message:
                        "Authorization token is required",
                },
                {
                    status: 401,
                }
            );
        }

        const body =
            await request.json();

        const response =
            await fetch(
                KUNDALI_MATCH_AGGREGATE_API,
                {
                    method: "POST",

                    headers: {
                        Accept:
                            "application/json",

                        "Content-Type":
                            "application/json",

                        Authorization:
                            authorization,
                    },

                    body: JSON.stringify(body),

                    cache: "no-store",
                }
            );

        const contentType =
            response.headers.get(
                "content-type"
            ) || "";

        let data: any;

        if (
            contentType.includes(
                "application/json"
            )
        ) {
            data =
                await response.json();
        } else {
            data =
                await response.text();
        }

        return NextResponse.json(
            data,
            {
                status: response.status,
            }
        );
    } catch (error: any) {
        console.error(
            "Kundali Match Aggregate API Error:",
            error
        );

        return NextResponse.json(
            {
                message:
                    error?.message ||
                    "Unable to match Kundli",
            },
            {
                status: 500,
            }
        );
    }
}
