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

// GET /api/customer-portal/[token] - Access customer portal data
export async function GET(
  request: NextRequest,
  { params }: { params: { token: string } }
) {
  try {
    const { token } = params;

    // Verify token
    const access = await prisma.customerPortalAccess.findUnique({
      where: { accessToken: token },
    });

    if (!access || (access.tokenExpiry && access.tokenExpiry < new Date())) {
      return NextResponse.json(
        { error: 'Invalid or expired token' },
        { status: 401 }
      );
    }

    // Update last accessed
    await prisma.customerPortalAccess.update({
      where: { id: access.id },
      data: { lastAccessedAt: new Date() },
    });

    // Get contract data
    const contract = await prisma.contract.findUnique({
      where: { id: access.contractId || '' },
      include: {
        quote: {
          include: {
            lead: true,
          },
        },
      },
    });

    // Get milestones
    const milestones = await prisma.projectMilestone.findMany({
      where: { contractId: contract?.id },
      orderBy: { createdAt: 'asc' },
    });

    // Get photos
    const photos = await prisma.fileUpload.findMany({
      where: { contractId: contract?.id },
      orderBy: { createdAt: 'desc' },
    });

    // Get vehicle tracking (last 24 hours)
    const tracking = await prisma.vehicleTracking.findMany({
      where: {
        contractId: contract?.id,
        timestamp: {
          gte: new Date(Date.now() - 24 * 60 * 60 * 1000),
        },
      },
      orderBy: { timestamp: 'desc' },
      take: 100,
    });

    return NextResponse.json({
      contract,
      milestones,
      photos,
      tracking,
      permissions: {
        canViewTracking: access.canViewTracking,
        canViewPhotos: access.canViewPhotos,
        canViewSchedule: access.canViewSchedule,
        canViewMilestones: access.canViewMilestones,
      },
    });
  } catch (error) {
    console.error('Error accessing customer portal:', error);
    return NextResponse.json(
      { error: 'Failed to access portal' },
      { status: 500 }
    );
  }
}
