import { NextResponse } from 'next/server';

const API_BASE = 'https://api.socialbuddy.co/api/users';

const normalizeUser = (u: any) => ({
    userid: u._id,
    name: u.name,
    email: u.email,
    mobileNumber:
        u.mobileNumber ||
        u.mobile ||
        u.phone ||
        u.phonenumber ||
        '',
    role: u.role,
});

// GET users
export async function GET() {
    const res = await fetch(API_BASE, {
        credentials: 'include',
    });
    const data = await res.json();
    return NextResponse.json(data.map(normalizeUser));
}

// ✅ ADD USER (ADMIN ONLY)
export async function POST(req: Request) {
    const body = await req.json();

    const res = await fetch(`${API_BASE}/create`, {
        method: 'POST',

        //  REQUIRED
        credentials: 'include',

        headers: {
            'Content-Type': 'application/json',

            //  THIS LINE IS WHY ADD USER WAS FAILING
            Cookie: req.headers.get('cookie') || '',
        },

        body: JSON.stringify(body),
    });

    if (!res.ok) {
        const error = await res.text();
        return NextResponse.json(
            { error },
            { status: res.status }
        );
    }

    const data = await res.json();
    return NextResponse.json(normalizeUser(data));
}
