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

export const dynamic = 'force-dynamic';

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

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

    if (userId) {
      if (includePublic) {
        where.OR = [{ createdById: userId }, { isPublic: true }];
      } else {
        where.createdById = userId;
      }
    } else if (includePublic) {
      where.isPublic = true;
    }

    if (module) where.module = module;

    const customReports = await prisma.customReport.findMany({
      where,
      include: {
        creator: { select: { id: true, name: true, email: true } },
      },
      orderBy: { updatedAt: 'desc' },
    });

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

// POST - Create custom report
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const {
      name,
      description,
      createdById,
      module,
      reportType,
      dataSources,
      layout,
      widgets,
      filters,
      defaultFilters,
      styling,
      permissions,
      isPublic,
      isTemplate,
    } = body;

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

    const customReport = await prisma.customReport.create({
      data: {
        name,
        description,
        createdById,
        module,
        reportType: reportType || 'mixed',
        dataSources: dataSources || [],
        layout: layout || {},
        widgets: widgets || [],
        filters: filters || [],
        defaultFilters: defaultFilters || {},
        styling: styling || {},
        permissions: permissions || {},
        isPublic: isPublic || false,
        isTemplate: isTemplate || false,
      },
      include: {
        creator: { select: { id: true, name: true, email: true } },
      },
    });

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

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

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

    // Increment version on update
    const customReport = await prisma.customReport.update({
      where: { id },
      data: {
        ...updates,
        version: { increment: 1 },
      },
      include: {
        creator: { select: { id: true, name: true, email: true } },
      },
    });

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

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

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

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

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