import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';

// GET: fetch role permissions + users per role + role activity logs
export async function GET(req: NextRequest) {
  const supabase = await createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const { searchParams } = new URL(req.url);
  const type = searchParams.get('type') || 'permissions';

  try {
    if (type === 'permissions') {
      const { data, error } = await supabase
        .from('role_permissions')
        .select('*')
        .order('role');
      if (error) throw error;
      return NextResponse.json({ permissions: data || [] });
    }

    if (type === 'users') {
      const { data, error } = await supabase
        .from('user_profiles')
        .select('id, email, full_name, role, is_active, created_at, avatar_url')
        .order('role')
        .order('full_name');
      if (error) throw error;

      // Group by role
      const grouped: Record<string, typeof data> = {};
      for (const u of data || []) {
        if (!grouped[u.role]) grouped[u.role] = [];
        grouped[u.role]!.push(u);
      }
      return NextResponse.json({ users: data || [], grouped });
    }

    if (type === 'activity') {
      const role = searchParams.get('role') || 'all';
      const limit = parseInt(searchParams.get('limit') || '50');

      let query = supabase
        .from('audit_logs')
        .select(`
          id, action, performed_by, performed_by_email,
          affected_item_id, affected_item_type, affected_item_title,
          old_value, new_value, metadata, created_at,
          user_profiles:performed_by ( full_name, email, role )
        `)
        .order('created_at', { ascending: false })
        .limit(limit);

      // Filter by role if specified
      if (role !== 'all') {
        // Get user IDs with that role
        const { data: roleUsers } = await supabase
          .from('user_profiles')
          .select('id')
          .eq('role', role);
        const ids = (roleUsers || []).map((u: { id: string }) => u.id);
        if (ids.length > 0) {
          query = query.in('performed_by', ids);
        } else {
          return NextResponse.json({ logs: [] });
        }
      }

      const { data, error } = await query;
      if (error) throw error;
      return NextResponse.json({ logs: data || [] });
    }

    return NextResponse.json({ error: 'Invalid type' }, { status: 400 });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : 'Unknown error';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}

// PATCH: update role permissions OR assign role to user
export async function PATCH(req: NextRequest) {
  const supabase = await createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const body = await req.json();

  try {
    // Assign role to user
    if (body.userId && body.newRole) {
      const { data: targetUser } = await supabase
        .from('user_profiles')
        .select('role, email, full_name')
        .eq('id', body.userId)
        .single();

      const { error } = await supabase
        .from('user_profiles')
        .update({ role: body.newRole })
        .eq('id', body.userId);
      if (error) throw error;

      // Log the role assignment
      const { data: performer } = await supabase
        .from('user_profiles')
        .select('email')
        .eq('id', user.id)
        .single();

      await supabase.from('audit_logs').insert({
        action: 'user_role_changed',
        performed_by: user.id,
        performed_by_email: performer?.email || user.email,
        affected_item_id: body.userId,
        affected_item_type: 'user',
        affected_item_title: targetUser?.full_name || targetUser?.email || body.userId,
        old_value: { role: targetUser?.role },
        new_value: { role: body.newRole },
      });

      return NextResponse.json({ success: true });
    }

    // Update role permissions
    if (body.role && body.permissions) {
      const { error } = await supabase
        .from('role_permissions')
        .update({ ...body.permissions, updated_at: new Date().toISOString() })
        .eq('role', body.role);
      if (error) throw error;

      // Log the permission update
      const { data: performer } = await supabase
        .from('user_profiles')
        .select('email')
        .eq('id', user.id)
        .single();

      await supabase.from('audit_logs').insert({
        action: 'role_permission_updated',
        performed_by: user.id,
        performed_by_email: performer?.email || user.email,
        affected_item_id: body.role,
        affected_item_type: 'role',
        affected_item_title: `${body.role} permissions`,
        old_value: null,
        new_value: body.permissions,
      });

      return NextResponse.json({ success: true });
    }

    return NextResponse.json({ error: 'Invalid request body' }, { status: 400 });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : 'Unknown error';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
