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

export const dynamic = 'force-dynamic';

// GET - Fetch documents and contracts
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const type = searchParams.get('type') || 'summary';

    if (type === 'documents') {
      const category = searchParams.get('category');
      const documents = await prisma.document.findMany({
        where: {
          status: { not: 'deleted' },
          ...(category ? { category } : {}),
        },
        orderBy: { createdAt: 'desc' },
        take: 100,
      });
      return NextResponse.json({ success: true, documents });
    }

    if (type === 'contracts') {
      const status = searchParams.get('status');
      const contracts = await prisma.contract.findMany({
        where: status ? { status } : {},
        orderBy: { createdAt: 'desc' },
        take: 100,
      });
      return NextResponse.json({ success: true, contracts });
    }

    // Summary
    const [documents, contracts, expiringContracts] = await Promise.all([
      prisma.document.findMany({ where: { status: 'active' } }),
      prisma.contract.findMany(),
      prisma.contract.findMany({
        where: {
          status: 'active',
          endDate: {
            lte: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30 days
            gte: new Date(),
          },
        },
        orderBy: { endDate: 'asc' },
        take: 5,
      }),
    ]);

    const docsByType = documents.reduce((acc: any, doc: any) => {
      acc[doc.type] = (acc[doc.type] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);

    const contractsByStatus = contracts.reduce((acc: any, c: any) => {
      acc[c.status] = (acc[c.status] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);

    const activeContractValue = contracts
      .filter((c: any) => c.status === 'active')
      .reduce((sum: number, c: any) => sum + (c.value || 0), 0);

    return NextResponse.json({
      success: true,
      summary: {
        totalDocuments: documents.length,
        documentsByType: docsByType,
        totalContracts: contracts.length,
        contractsByStatus,
        activeContractValue,
        expiringContractsCount: expiringContracts.length,
        totalStorageUsed: documents.reduce((sum: number, d: any) => sum + (d.fileSize || 0), 0),
      },
      recentDocuments: documents.slice(0, 5),
      expiringContracts,
    });
  } catch (error) {
    console.error('Documents API error:', error);
    return NextResponse.json({ success: false, error: 'Failed to fetch documents data' }, { status: 500 });
  }
}

// POST - Create new document or contract
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { entity, data } = body;

    if (entity === 'document') {
      const document = await prisma.document.create({ data });
      return NextResponse.json({ success: true, document });
    }

    if (entity === 'contract') {
      const contract = await prisma.contract.create({ data });
      return NextResponse.json({ success: true, contract });
    }

    return NextResponse.json({ success: false, error: 'Invalid entity type' }, { status: 400 });
  } catch (error) {
    console.error('Documents POST error:', error);
    return NextResponse.json({ success: false, error: 'Failed to create record' }, { status: 500 });
  }
}

// PATCH - Update document/contract
export async function PATCH(request: NextRequest) {
  try {
    const body = await request.json();
    const { entity, id, data } = body;

    if (entity === 'document') {
      const document = await prisma.document.update({
        where: { id },
        data,
      });
      return NextResponse.json({ success: true, document });
    }

    if (entity === 'contract') {
      const contract = await prisma.contract.update({
        where: { id },
        data,
      });
      return NextResponse.json({ success: true, contract });
    }

    return NextResponse.json({ success: false, error: 'Invalid entity type' }, { status: 400 });
  } catch (error) {
    console.error('Documents PATCH error:', error);
    return NextResponse.json({ success: false, error: 'Failed to update record' }, { status: 500 });
  }
}

// DELETE - Archive/soft-delete document
export async function DELETE(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const id = searchParams.get('id');
    const entity = searchParams.get('entity') || 'document';

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

    if (entity === 'document') {
      await prisma.document.update({
        where: { id },
        data: { status: 'deleted' },
      });
      return NextResponse.json({ success: true });
    }

    if (entity === 'contract') {
      await prisma.contract.update({
        where: { id },
        data: { status: 'terminated' },
      });
      return NextResponse.json({ success: true });
    }

    return NextResponse.json({ success: false, error: 'Invalid entity type' }, { status: 400 });
  } catch (error) {
    console.error('Documents DELETE error:', error);
    return NextResponse.json({ success: false, error: 'Failed to delete record' }, { status: 500 });
  }
}
