import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';

export async function POST(req: NextRequest) {
  try {
    const { userId, roleId } = await req.json();

    if (!userId || !roleId) {
      return NextResponse.json(
        { success: false, error: 'User ID and Role ID are required' },
        { status: 400 }
      );
    }

    // Verify user exists
    const user = await db.user.findUnique({ where: { id: userId } });
    if (!user) {
      return NextResponse.json(
        { success: false, error: 'User not found' },
        { status: 404 }
      );
    }

    // Verify role exists
    const role = await db.role.findUnique({ where: { id: roleId } });
    if (!role) {
      return NextResponse.json(
        { success: false, error: 'Role not found' },
        { status: 404 }
      );
    }

    // Check if already assigned
    const existing = await db.userRole.findUnique({
      where: { userId_roleId: { userId, roleId } },
    });

    if (existing) {
      return NextResponse.json(
        { success: false, error: 'Role already assigned to this user' },
        { status: 409 }
      );
    }

    const userRole = await db.userRole.create({
      data: { userId, roleId },
      include: {
        role: { select: { id: true, name: true, label: true, color: true } },
      },
    });

    return NextResponse.json({ success: true, userRole }, { status: 201 });
  } catch (error) {
    console.error('Assign role error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to assign role' },
      { status: 500 }
    );
  }
}

export async function DELETE(req: NextRequest) {
  try {
    const { userId, roleId } = await req.json();

    if (!userId || !roleId) {
      return NextResponse.json(
        { success: false, error: 'User ID and Role ID are required' },
        { status: 400 }
      );
    }

    const existing = await db.userRole.findUnique({
      where: { userId_roleId: { userId, roleId } },
    });

    if (!existing) {
      return NextResponse.json(
        { success: false, error: 'Role assignment not found' },
        { status: 404 }
      );
    }

    await db.userRole.delete({
      where: { userId_roleId: { userId, roleId } },
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Remove role error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to remove role' },
      { status: 500 }
    );
  }
}
