import { NextRequest, NextResponse } from 'next/server';
import { getSupabaseAdmin } from '@/lib/supabase/server';
import type { FeedbackUpdateInput } from '@/lib/types/feedback';

const VALID_STATUSES = ['new', 'triaged', 'in_progress', 'resolved', 'wont_fix'];
const VALID_SEVERITIES = ['critical', 'high', 'medium', 'low'];

/**
 * PATCH /api/feedback/[id] - Update feedback (admin only)
 */
export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const pin = request.headers.get('x-ceo-pin');
    if (pin !== '5050') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

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

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

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

    // Auto-set resolved_at when marking resolved
    if (body.status === 'resolved') {
      updates.resolved_at = new Date().toISOString();
    } else if (body.status) {
      updates.resolved_at = null;
    }

    const serviceClient = getSupabaseAdmin();
    const { data, error } = await serviceClient
      .from('feedback')
      .update(updates)
      .eq('id', id)
      .select()
      .single();

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

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

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