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

export async function GET() {
  try {
    const roles = await db.role.findMany({
      include: {
        permissions: {
          orderBy: { module: 'asc' },
        },
        _count: {
          select: { userRoles: true },
        },
      },
      orderBy: { createdAt: 'asc' },
    });

    return NextResponse.json({ success: true, roles });
  } catch (error) {
    console.error('Fetch roles error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to fetch roles' },
      { status: 500 }
    );
  }
}

export async function POST(req: NextRequest) {
  try {
    const { name, label, description, color, permissions } = await req.json();

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

    // Check if role name already exists
    const existing = await db.role.findUnique({ where: { name } });
    if (existing) {
      return NextResponse.json(
        { success: false, error: 'Role name already exists' },
        { status: 409 }
      );
    }

    const role = await db.role.create({
      data: {
        name,
        label,
        description: description || null,
        color: color || '#f97316',
        permissions: {
          create: (permissions || []).map(
            (p: {
              module: string;
              canView?: boolean;
              canCreate?: boolean;
              canEdit?: boolean;
              canDelete?: boolean;
            }) => ({
              module: p.module,
              canView: p.canView || false,
              canCreate: p.canCreate || false,
              canEdit: p.canEdit || false,
              canDelete: p.canDelete || false,
            })
          ),
        },
      },
      include: { permissions: true },
    });

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

export async function PATCH(req: NextRequest) {
  try {
    const { id, name, label, description, color, permissions } = await req.json();

    if (!id) {
      return NextResponse.json(
        { success: false, error: 'Role ID is required' },
        { status: 400 }
      );
    }

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

    // Build update data
    const updateData: {
      name?: string;
      label?: string;
      description?: string | null;
      color?: string;
    } = {};

    if (name !== undefined) updateData.name = name;
    if (label !== undefined) updateData.label = label;
    if (description !== undefined) updateData.description = description;
    if (color !== undefined) updateData.color = color;

    // Update basic role info
    await db.role.update({
      where: { id },
      data: updateData,
    });

    // Update permissions if provided
    if (permissions && Array.isArray(permissions)) {
      // Delete existing permissions and recreate
      await db.rolePermission.deleteMany({ where: { roleId: id } });

      if (permissions.length > 0) {
        await db.rolePermission.createMany({
          data: permissions.map(
            (p: {
              module: string;
              canView?: boolean;
              canCreate?: boolean;
              canEdit?: boolean;
              canDelete?: boolean;
            }) => ({
              roleId: id,
              module: p.module,
              canView: p.canView || false,
              canCreate: p.canCreate || false,
              canEdit: p.canEdit || false,
              canDelete: p.canDelete || false,
            })
          ),
        });
      }
    }

    const updatedRole = await db.role.findUnique({
      where: { id },
      include: { permissions: { orderBy: { module: 'asc' } } },
    });

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

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

    if (!id) {
      return NextResponse.json(
        { success: false, error: 'Role ID is required' },
        { status: 400 }
      );
    }

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

    // Prevent deleting the super_admin role
    if (existing.name === 'super_admin') {
      return NextResponse.json(
        { success: false, error: 'Cannot delete the super_admin role' },
        { status: 403 }
      );
    }

    // Cascading deletes will handle permissions and userRoles
    await db.role.delete({ where: { id } });

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