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

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

    const where = teamId ? { teamId } : {};
    const members = await db.teamMember.findMany({
      where,
      include: {
        user: { select: { id: true, name: true, email: true, roles: true } },
        team: { select: { id: true, name: true } },
      },
    });

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

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

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

    await db.teamMember.create({
      data: {
        teamId,
        userId,
        role: role || 'member',
        permissions: permissions ? JSON.stringify(permissions) : '[]',
      },
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Add team member error:', error);
    return NextResponse.json({ success: false, error: 'Failed to add team member' }, { status: 500 });
  }
}

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

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

    const updateData: Record<string, unknown> = {};
    if (role !== undefined) updateData.role = role;
    if (permissions !== undefined) updateData.permissions = JSON.stringify(permissions);

    await db.teamMember.update({ where: { id }, data: updateData });

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

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

    // Support both: delete by member `id` OR by `teamId` + `userId` combination
    if (id) {
      await db.teamMember.delete({ where: { id } });
    } else if (teamId && userId) {
      await db.teamMember.delete({
        where: { teamId_userId: { teamId, userId } },
      });
    } else {
      return NextResponse.json(
        { success: false, error: 'Either member ID or both teamId and userId are required' },
        { status: 400 }
      );
    }

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