// ============================================================
// GET /api/v1/account/members
// Lists every member of the account (API-key scoped).
// ============================================================

import { requireApiKey } from '@/lib/auth/api-context';
import { ok, fail, toApiErrorResponse } from '@/lib/api/v1/respond';
import { isAccountRole } from '@/lib/auth/roles';

interface ProfileRow {
  user_id: string;
  full_name: string | null;
  email: string | null;
  avatar_url: string | null;
  account_role: string;
  created_at: string;
}

export async function GET(request: Request) {
  try {
    const ctx = await requireApiKey(request, 'conversations:read');

    const { data, error } = await ctx.supabase
      .from('profiles')
      .select('user_id, full_name, email, avatar_url, account_role, created_at')
      .eq('account_id', ctx.accountId)
      .order('created_at', { ascending: true });

    if (error) {
      console.error('[api/v1/account/members] fetch error:', error);
      return fail('internal', 'Failed to load members', 500);
    }

    const members = (data as ProfileRow[]).flatMap((row) => {
      if (!isAccountRole(row.account_role)) return [];
      return [
        {
          id: row.user_id,
          name: row.full_name ?? row.email ?? row.user_id,
          email: row.email,
          avatar_url: row.avatar_url,
          role: row.account_role,
          joined_at: row.created_at,
        },
      ];
    });

    return ok({ members });
  } catch (err) {
    return toApiErrorResponse(err);
  }
}
