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

// GET: Fetch satisfaction surveys
export async function GET(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const searchParams = request.nextUrl.searchParams;
    const contractId = searchParams.get('contractId');
    const customerId = searchParams.get('customerId');
    const completed = searchParams.get('completed') === 'true';

    const where: any = {};
    if (contractId) where.contractId = contractId;
    if (customerId) where.customerId = customerId;
    if (completed) {
      where.completedAt = { not: null };
    }

    const surveys = await prisma.satisfactionSurvey.findMany({
      where,
      orderBy: { createdAt: 'desc' },
    });

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

// POST: Create a new satisfaction survey
export async function POST(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

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

    // Check if survey already exists
    const existingSurvey = await prisma.satisfactionSurvey.findUnique({
      where: { contractId },
    });

    if (existingSurvey) {
      return NextResponse.json(
        { error: 'Survey already exists for this contract' },
        { status: 400 }
      );
    }

    const survey = await prisma.satisfactionSurvey.create({
      data: {
        contractId,
        customerId: session.user.id,
        contractorId,
        sentAt: new Date(),
      },
    });

    return NextResponse.json({ survey }, { status: 201 });
  } catch (error) {
    console.error('Error creating survey:', error);
    return NextResponse.json(
      { error: 'Failed to create survey' },
      { status: 500 }
    );
  }
}

// PUT: Submit survey response
export async function PUT(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json();
    const {
      surveyId,
      workQuality,
      timeline,
      communication,
      cleanliness,
      professionalism,
      overallSatisfaction,
      npsScore,
      positives,
      improvements,
      testimonial,
      canUseTestimonial,
    } = body;

    const survey = await prisma.satisfactionSurvey.findUnique({
      where: { id: surveyId },
    });

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

    if (survey.customerId !== session.user.id) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    // Calculate NPS category
    let npsCategory: 'DETRACTOR' | 'PASSIVE' | 'PROMOTER' | undefined;
    if (npsScore !== undefined) {
      if (npsScore <= 6) npsCategory = 'DETRACTOR';
      else if (npsScore <= 8) npsCategory = 'PASSIVE';
      else npsCategory = 'PROMOTER';
    }

    const updatedSurvey = await prisma.satisfactionSurvey.update({
      where: { id: surveyId },
      data: {
        workQuality,
        timeline,
        communication,
        cleanliness,
        professionalism,
        overallSatisfaction,
        npsScore,
        positives,
        improvements,
        testimonial,
        canUseTestimonial,
        completedAt: new Date(),
      },
    });

    // Create NPS response if score provided
    if (npsScore !== undefined && npsCategory) {
      await prisma.nPSResponse.create({
        data: {
          contractId: survey.contractId,
          customerId: session.user.id,
          score: npsScore,
          category: npsCategory,
          feedback: improvements,
        },
      });
    }

    // If testimonial provided and permission granted, create a review
    if (testimonial && canUseTestimonial && overallSatisfaction) {
      await prisma.contractorReview.create({
        data: {
          contractId: survey.contractId,
          contractorId: survey.contractorId,
          customerId: session.user.id,
          overallRating: overallSatisfaction,
          qualityRating: workQuality,
          timelinessRating: timeline,
          communicationRating: communication,
          comment: testimonial,
          isVerified: true,
        },
      });
    }

    return NextResponse.json({ survey: updatedSurvey });
  } catch (error) {
    console.error('Error updating survey:', error);
    return NextResponse.json(
      { error: 'Failed to update survey' },
      { status: 500 }
    );
  }
}
