import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { createAdminClient } from '@/lib/supabase/admin';
import { ensureForumProfile } from '@/lib/forum/profile';

const EDITABLE_FIELDS = [
  'username',
  'display_name',
  'bio',
  'role_title',
  'company',
  'location_city',
  'location_country',
  'avatar_url',
] as const;

type EditableField = (typeof EDITABLE_FIELDS)[number];

export async function GET() {
  const supabase = await createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) {
    return NextResponse.json({ error: 'Not authenticated', auth_required: true }, { status: 401 });
  }
  const profile = await ensureForumProfile(user);
  return NextResponse.json({ profile });
}

export async function PATCH(req: NextRequest) {
  const supabase = await createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) {
    return NextResponse.json({ error: 'Not authenticated', auth_required: true }, { status: 401 });
  }

  const body = await req.json();
  const updates: Partial<Record<EditableField, string | null>> = {};
  for (const field of EDITABLE_FIELDS) {
    if (field in body) {
      const v = body[field];
      updates[field] = typeof v === 'string' ? v.trim() || null : null;
    }
  }

  if (updates.username) {
    const u = updates.username;
    if (!/^[a-z0-9_]{3,24}$/i.test(u)) {
      return NextResponse.json(
        { error: 'Username must be 3-24 characters, letters/numbers/underscore only.' },
        { status: 400 }
      );
    }
    updates.username = u.toLowerCase();
  }

  await ensureForumProfile(user);

  const admin = createAdminClient();
  const { data: updated, error } = await admin
    .from('forum_user_profiles')
    .update(updates)
    .eq('user_id', user.id)
    .select()
    .single();

  if (error) {
    if (error.code === '23505') {
      return NextResponse.json({ error: 'That username is already taken.' }, { status: 409 });
    }
    return NextResponse.json({ error: error.message }, { status: 500 });
  }

  return NextResponse.json({ profile: updated });
}
