
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { prisma } from '@/lib/db';
import { randomBytes } from 'crypto';

// POST /api/customer-portal/access - Grant customer portal access
export async function POST(request: NextRequest) {
  try {
    const session = await getServerSession();
    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json();
    const { customerId, contractId } = body;

    // Generate secure access token
    const accessToken = randomBytes(32).toString('hex');
    const tokenExpiry = new Date(Date.now() + 90 * 24 * 60 * 60 * 1000); // 90 days

    const access = await prisma.customerPortalAccess.upsert({
      where: { customerId },
      create: {
        customerId,
        contractId,
        accessToken,
        tokenExpiry,
      },
      update: {
        accessToken,
        tokenExpiry,
        contractId,
      },
    });

    return NextResponse.json({
      success: true,
      accessToken,
      portalUrl: `/customer-portal/${accessToken}`,
    });
  } catch (error) {
    console.error('Error granting portal access:', error);
    return NextResponse.json(
      { error: 'Failed to grant access' },
      { status: 500 }
    );
  }
}
