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

export async function POST(req: NextRequest) {
  try {
    const { teamId, menuId, canView, canEdit, canDelete } = await req.json();

    if (!teamId || !menuId) {
      return NextResponse.json({ success: false, error: 'Team ID and Menu ID are required' }, { status: 400 });
    }

    // Upsert the permission
    const existing = await db.teamMenu.findFirst({
      where: { teamId, menuId },
    });

    if (existing) {
      await db.teamMenu.update({
        where: { id: existing.id },
        data: {
          canView: canView !== undefined ? canView : existing.canView,
          canEdit: canEdit !== undefined ? canEdit : existing.canEdit,
          canDelete: canDelete !== undefined ? canDelete : existing.canDelete,
        },
      });
    } else {
      await db.teamMenu.create({
        data: {
          teamId,
          menuId,
          canView: canView !== false,
          canEdit: canEdit || false,
          canDelete: canDelete || false,
        },
      });
    }

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

export async function PATCH(req: NextRequest) {
  try {
    const { teamId, permissions } = await req.json();

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

    if (!permissions || !Array.isArray(permissions) || permissions.length === 0) {
      return NextResponse.json(
        { success: false, error: 'Permissions array is required' },
        { status: 400 }
      );
    }

    const results = [];

    for (const perm of permissions) {
      const { menuId, canView, canEdit, canDelete } = perm;

      if (!menuId) continue;

      // Use upsert via the unique compound key
      const existing = await db.teamMenu.findUnique({
        where: { teamId_menuId: { teamId, menuId } },
      });

      if (existing) {
        const updated = await db.teamMenu.update({
          where: { id: existing.id },
          data: {
            canView: canView !== undefined ? canView : existing.canView,
            canEdit: canEdit !== undefined ? canEdit : existing.canEdit,
            canDelete: canDelete !== undefined ? canDelete : existing.canDelete,
          },
        });
        results.push(updated);
      } else {
        const created = await db.teamMenu.create({
          data: {
            teamId,
            menuId,
            canView: canView !== false,
            canEdit: canEdit || false,
            canDelete: canDelete || false,
          },
        });
        results.push(created);
      }
    }

    return NextResponse.json({ success: true, permissions: results });
  } catch (error) {
    console.error('Batch update permissions error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to batch update permissions' },
      { status: 500 }
    );
  }
}

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const teamId = searchParams.get('teamId');

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

    const permissions = await db.teamMenu.findMany({
      where: { teamId },
      include: {
        menu: { select: { id: true, title: true, slug: true, path: true } },
      },
      orderBy: { menuId: 'asc' },
    });

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