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

const CEO_PIN = '5050';
const VALID_STATUSES: SuccessStoryStatus[] = ['candidate', 'contacted', 'agreed', 'published', 'declined'];

/**
 * GET /api/success-tracking/candidates - List success story candidates (admin only)
 */
export async function GET(request: NextRequest) {
  try {
    const pin = request.headers.get('x-ceo-pin') || new URL(request.url).searchParams.get('pin');
    if (pin !== CEO_PIN) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const admin = getSupabaseAdmin();
    const url = new URL(request.url);
    const status = url.searchParams.get('status');
    const userType = url.searchParams.get('user_type');
    const minScore = parseInt(url.searchParams.get('min_score') || '0');
    const limit = parseInt(url.searchParams.get('limit') || '50');

    let query = admin
      .from('success_candidates')
      .select('*')
      .gte('score', minScore)
      .order('score', { ascending: false })
      .limit(Math.min(limit, 200));

    if (status) query = query.eq('status', status);
    if (userType) query = query.eq('user_type', userType);

    const { data, error } = await query;

    if (error) {
      console.error('Candidates fetch error:', error);
      return NextResponse.json({ error: 'Failed to fetch candidates' }, { status: 500 });
    }

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

/**
 * PATCH /api/success-tracking/candidates - Update candidate status/notes (admin only)
 */
export async function PATCH(request: NextRequest) {
  try {
    const pin = request.headers.get('x-ceo-pin');
    if (pin !== CEO_PIN) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json();
    const { user_id, status, admin_notes } = body;

    if (!user_id) {
      return NextResponse.json({ error: 'user_id required' }, { status: 400 });
    }

    if (status && !VALID_STATUSES.includes(status)) {
      return NextResponse.json({ error: 'Invalid status' }, { status: 400 });
    }

    const admin = getSupabaseAdmin();
    const updates: Record<string, unknown> = {};
    if (status) updates.status = status;
    if (admin_notes !== undefined) updates.admin_notes = admin_notes;

    if (Object.keys(updates).length === 0) {
      return NextResponse.json({ error: 'No updates provided' }, { status: 400 });
    }

    const { data, error } = await admin
      .from('success_candidates')
      .update(updates)
      .eq('user_id', user_id)
      .select()
      .single();

    if (error) {
      console.error('Candidate update error:', error);
      return NextResponse.json({ error: 'Failed to update candidate' }, { status: 500 });
    }

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