// API Routes for Dashboard Layouts
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';

export const dynamic = 'force-dynamic';

// GET - List user's dashboards
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const userId = searchParams.get('userId');
    const module = searchParams.get('module');
    const includeShared = searchParams.get('includeShared') === 'true';

    if (!userId) {
      return NextResponse.json(
        { error: 'User ID required' },
        { status: 400 }
      );
    }

    const where: Record<string, unknown> = {};

    if (includeShared) {
      where.OR = [
        { userId },
        { isShared: true },
        { sharedWith: { array_contains: userId } },
      ];
    } else {
      where.userId = userId;
    }

    if (module) where.module = module;

    const dashboards = await prisma.dashboardLayout.findMany({
      where,
      include: {
        user: { select: { id: true, name: true } },
      },
      orderBy: [{ isDefault: 'desc' }, { updatedAt: 'desc' }],
    });

    return NextResponse.json({ dashboards });
  } catch (error) {
    console.error('Error fetching dashboards:', error);
    return NextResponse.json(
      { error: 'Failed to fetch dashboards' },
      { status: 500 }
    );
  }
}

// POST - Create dashboard
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const {
      name,
      description,
      userId,
      module,
      layout,
      widgets,
      filters,
      refreshInterval,
      isDefault,
      isShared,
      sharedWith,
    } = body;

    if (!name || !userId) {
      return NextResponse.json(
        { error: 'Missing required fields: name, userId' },
        { status: 400 }
      );
    }

    // If setting as default, unset other defaults
    if (isDefault) {
      await prisma.dashboardLayout.updateMany({
        where: { userId, isDefault: true },
        data: { isDefault: false },
      });
    }

    const dashboard = await prisma.dashboardLayout.create({
      data: {
        name,
        description,
        userId,
        module,
        layout: layout || {},
        widgets: widgets || [],
        filters: filters || {},
        refreshInterval,
        isDefault: isDefault || false,
        isShared: isShared || false,
        sharedWith: sharedWith || [],
      },
    });

    return NextResponse.json({
      success: true,
      dashboard,
    });
  } catch (error) {
    console.error('Error creating dashboard:', error);
    return NextResponse.json(
      { error: 'Failed to create dashboard' },
      { status: 500 }
    );
  }
}

// PATCH - Update dashboard
export async function PATCH(request: NextRequest) {
  try {
    const body = await request.json();
    const { id, userId, ...updates } = body;

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

    // If setting as default, unset other defaults
    if (updates.isDefault && userId) {
      await prisma.dashboardLayout.updateMany({
        where: { userId, isDefault: true, id: { not: id } },
        data: { isDefault: false },
      });
    }

    const dashboard = await prisma.dashboardLayout.update({
      where: { id },
      data: {
        ...updates,
        version: { increment: 1 },
      },
    });

    return NextResponse.json({
      success: true,
      dashboard,
    });
  } catch (error) {
    console.error('Error updating dashboard:', error);
    return NextResponse.json(
      { error: 'Failed to update dashboard' },
      { status: 500 }
    );
  }
}

// DELETE - Delete dashboard
export async function DELETE(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const id = searchParams.get('id');

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

    await prisma.dashboardLayout.delete({ where: { id } });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error deleting dashboard:', error);
    return NextResponse.json(
      { error: 'Failed to delete dashboard' },
      { status: 500 }
    );
  }
}
