/**
 * Individual Portfolio Site API Route
 * GET /api/portfolio/sites/[id] - Get site details
 * PATCH /api/portfolio/sites/[id] - Update site settings
 * DELETE /api/portfolio/sites/[id] - Delete site
 */

import { NextRequest, NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';
import { AuthMiddleware } from '@/lib/auth';
import { ComplianceService } from '@/lib/compliance';

const prisma = new PrismaClient();

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const authResult = await AuthMiddleware.requireRole(request, 'ADMIN');
    if (authResult instanceof NextResponse) {
      return authResult;
    }

    const { id } = await params;

    const site = await prisma.portfolioSite.findUnique({
      where: { id },
    });

    if (!site) {
      return NextResponse.json(
        { error: 'Site not found' },
        { status: 404 }
      );
    }

    return NextResponse.json({ site });
  } catch (error) {
    console.error('[API] Get portfolio site error:', error);
    return NextResponse.json(
      { error: 'Failed to fetch site' },
      { status: 500 }
    );
  }
}

interface UpdateSiteBody {
  name?: string;
  campaignTemplate?: string;
  autoOptimize?: boolean;
  priorityScore?: number;
  status?: string;
}

export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const authResult = await AuthMiddleware.requireRole(request, 'ADMIN');
    if (authResult instanceof NextResponse) {
      return authResult;
    }

    const { id } = await params;
    const body: UpdateSiteBody = await request.json();

    const site = await prisma.portfolioSite.findUnique({
      where: { id },
    });

    if (!site) {
      return NextResponse.json(
        { error: 'Site not found' },
        { status: 404 }
      );
    }

    const updatedSite = await prisma.portfolioSite.update({
      where: { id },
      data: {
        name: body.name ?? site.name,
        campaignTemplate: body.campaignTemplate ?? site.campaignTemplate,
        autoOptimize: body.autoOptimize ?? site.autoOptimize,
        priorityScore: body.priorityScore ?? site.priorityScore,
        status: body.status ?? site.status,
        updatedAt: new Date(),
      },
    });

    await ComplianceService.log('AGENT', 'PORTFOLIO_SITE_UPDATED', 'PortfolioAPI', {
      siteId: id,
      domain: site.domain,
      changes: body,
    });

    return NextResponse.json({
      site: updatedSite,
      message: 'Site updated successfully',
    });
  } catch (error) {
    console.error('[API] Update portfolio site error:', error);
    return NextResponse.json(
      { error: 'Failed to update site' },
      { status: 500 }
    );
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const authResult = await AuthMiddleware.requireRole(request, 'ADMIN');
    if (authResult instanceof NextResponse) {
      return authResult;
    }

    const { id } = await params;

    const site = await prisma.portfolioSite.findUnique({
      where: { id },
    });

    if (!site) {
      return NextResponse.json(
        { error: 'Site not found' },
        { status: 404 }
      );
    }

    // Delete related data first (if any)
    await prisma.sERPFeature.deleteMany({
      where: { siteId: id },
    });

    await prisma.backlinkOpportunity.deleteMany({
      where: { siteId: id },
    });

    // Delete the site
    await prisma.portfolioSite.delete({
      where: { id },
    });

    await ComplianceService.log('AGENT', 'PORTFOLIO_SITE_DELETED', 'PortfolioAPI', {
      siteId: id,
      domain: site.domain,
    });

    return NextResponse.json({
      message: 'Site deleted successfully',
    });
  } catch (error) {
    console.error('[API] Delete portfolio site error:', error);
    return NextResponse.json(
      { error: 'Failed to delete site' },
      { status: 500 }
    );
  }
}
