import { NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';
import { z } from 'zod';

const prisma = new PrismaClient();

const userSchema = z.object({
    email: z.string().email(),
    firstName: z.string().min(1),
    lastName: z.string().min(1),
    city: z.string().min(1),
    country: z.string().min(1),
    address: z.string().min(1),
    phone: z.string().min(1),
    password: z.string().min(6),
    role: z.enum(['ADMIN', 'MANAGER']),
});

// CREATE User
export async function POST(req: Request) {
    try {
        const body = await req.json();
        const data = userSchema.parse(body);
        const user = await prisma.user.create({ data });
        return NextResponse.json(user, { status: 201 });
    } catch (error:any) {
        return NextResponse.json({ error: error.message }, { status: 400 });
    }
}

// GET ALL Users
export async function GET() {
    try {
        const users = await prisma.user.findMany();
        return NextResponse.json(users, { status: 200 });
    } catch (error) {
        return NextResponse.json({ error: 'Failed to fetch users' }, { status: 500 });
    }
}

// PATCH User (update)
export async function PATCH(req: Request) {
    try {
        const body = await req.json();
        const { id, ...data } = body;
        if (!id) {
            return NextResponse.json({ error: 'User ID is required' }, { status: 400 });
        }
        // Log pour diagnostic
        console.log('[PATCH /api/users] body:', body);
        console.log('[PATCH /api/users] data envoyé à Prisma:', data);
        // On autorise la mise à jour partielle (tous les champs sont optionnels sauf id)
        const user = await prisma.user.update({
            where: { id },
            data,
        });
        return NextResponse.json(user, { status: 200 });
    } catch (error:any) {
        return NextResponse.json({ error: error.message }, { status: 400 });
    }
}

// DELETE User
export async function DELETE(req: Request) {
    try {
        const { id } = await req.json();
        await prisma.user.delete({ where: { id } });
        return NextResponse.json({ message: 'User deleted' }, { status: 200 });
    } catch (error) {
        return NextResponse.json({ error: 'Failed to delete user' }, { status: 400 });
    }
}