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

export async function GET() {
  try {
    const teams = await db.team.findMany({
      orderBy: { createdAt: 'desc' },
      include: {
        members: {
          include: {
            user: { select: { id: true, name: true, email: true } },
          },
        },
        teamMenus: {
          include: {
            menu: { select: { id: true, title: true, slug: true } },
          },
        },
      },
    });
    return NextResponse.json({ success: true, teams });
  } catch (error) {
    console.error('Fetch teams error:', error);
    return NextResponse.json({ success: false, error: 'Failed to fetch teams' }, { status: 500 });
  }
}

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

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

    await db.team.create({
      data: { name, description: description || null },
    });

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

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

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

    const updateData: Record<string, unknown> = {};
    if (name !== undefined) updateData.name = name;
    if (description !== undefined) updateData.description = description;
    if (isActive !== undefined) updateData.isActive = isActive;

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

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

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

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

    await db.team.delete({ where: { id } });

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