import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { recordMilestone } from '@/lib/success-tracking';
import type { SurveyType } from '@/lib/types/success-tracking';

const VALID_SURVEY_TYPES: SurveyType[] = ['onboarding', 'post_hire', 'exit'];

/**
 * POST /api/success-tracking/survey - Submit a survey
 */
export async function POST(request: NextRequest) {
  try {
    const supabase = await createClient();
    const { data: { user } } = await supabase.auth.getUser();

    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json();
    const { survey_type, responses, nps_score } = body;

    // Validate survey type
    if (!survey_type || !VALID_SURVEY_TYPES.includes(survey_type)) {
      return NextResponse.json({ error: 'Invalid survey type' }, { status: 400 });
    }

    // Validate responses
    if (!responses || typeof responses !== 'object' || Object.keys(responses).length === 0) {
      return NextResponse.json({ error: 'Responses required' }, { status: 400 });
    }

    // Validate NPS if provided
    if (nps_score !== undefined && nps_score !== null) {
      const score = Number(nps_score);
      if (isNaN(score) || score < 0 || score > 10) {
        return NextResponse.json({ error: 'NPS score must be 0-10' }, { status: 400 });
      }
    }

    // Get user type
    const { data: profile } = await supabase
      .from('profiles')
      .select('type')
      .eq('id', user.id)
      .single();

    const userType = profile?.type || 'worker';

    // Insert survey
    const { data, error } = await supabase
      .from('success_surveys')
      .insert({
        user_id: user.id,
        user_type: userType,
        survey_type,
        responses,
        nps_score: nps_score ?? null,
      })
      .select()
      .single();

    if (error) {
      // Unique constraint — already submitted this survey type
      if (error.code === '23505') {
        return NextResponse.json(
          { error: 'You have already completed this survey' },
          { status: 409 }
        );
      }
      console.error('Survey insert error:', error);
      return NextResponse.json({ error: 'Failed to submit survey' }, { status: 500 });
    }

    // If onboarding survey, check if it has a referral source
    if (survey_type === 'onboarding' && responses.how_found === 'Friend/colleague') {
      // Could be a referral — flag for tracking
      await recordMilestone(user.id, userType, 'signup', { referred: true });
    }

    return NextResponse.json({ data }, { status: 201 });
  } catch (err) {
    console.error('Survey API error:', err);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

/**
 * GET /api/success-tracking/survey?type=onboarding - Check if user has completed a survey
 */
export async function GET(request: NextRequest) {
  try {
    const supabase = await createClient();
    const { data: { user } } = await supabase.auth.getUser();

    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const url = new URL(request.url);
    const surveyType = url.searchParams.get('type');

    if (!surveyType || !VALID_SURVEY_TYPES.includes(surveyType as SurveyType)) {
      return NextResponse.json({ error: 'Invalid survey type' }, { status: 400 });
    }

    const { data, error } = await supabase
      .from('success_surveys')
      .select('id, survey_type, created_at')
      .eq('user_id', user.id)
      .eq('survey_type', surveyType)
      .limit(1);

    if (error) {
      return NextResponse.json({ error: 'Failed to check survey' }, { status: 500 });
    }

    return NextResponse.json({
      completed: data && data.length > 0,
      survey: data?.[0] || null,
    });
  } catch (err) {
    console.error('Survey GET error:', err);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
