import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};

/**
 * Admin team management.
 * Operations:
 *   - grant_admin   { target_user_id?: uuid, target_phone?: string, role?: 'admin'|'super_admin' }
 *   - revoke_admin  { target_user_id?: uuid, target_phone?: string }
 *   - list_admins   {}
 *
 * Caller MUST be a super_admin (verified via user_roles table).
 */
serve(async (req) => {
  if (req.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders });
  }

  const json = (status: number, body: unknown) =>
    new Response(JSON.stringify(body), {
      status,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });

  try {
    const authHeader = req.headers.get('Authorization');
    if (!authHeader) return json(401, { error: '未授权访问' });

    const SUPABASE_URL = Deno.env.get('SUPABASE_URL') ?? '';
    const ANON_KEY = Deno.env.get('SUPABASE_ANON_KEY') ?? '';
    const SERVICE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '';

    // Caller-scoped client (to identify the requester)
    const supabase = createClient(SUPABASE_URL, ANON_KEY, {
      auth: { persistSession: false, autoRefreshToken: false },
      global: { headers: { Authorization: authHeader } },
    });

    // Service-role client for privileged writes (RLS bypass) — never returned to client.
    const admin = createClient(SUPABASE_URL, SERVICE_KEY, {
      auth: { persistSession: false, autoRefreshToken: false },
    });

    const { data: { user }, error: userErr } = await supabase.auth.getUser();
    if (userErr || !user) return json(401, { error: '用户未认证' });

    // Verify caller is super_admin
    const { data: callerRoles, error: roleErr } = await admin
      .from('user_roles')
      .select('role')
      .eq('user_id', user.id);
    if (roleErr) return json(500, { error: roleErr.message });

    const isSuperAdmin = (callerRoles ?? []).some((r) => r.role === 'super_admin');
    if (!isSuperAdmin) {
      return json(403, { error: '仅超级管理员可管理团队成员' });
    }

    const body = await req.json().catch(() => ({}));
    const { operation, params = {} } = body as { operation: string; params: Record<string, any> };
    console.log('[admin-team]', operation, params);

    // Helper: resolve target user_id from either user_id or phone
    const resolveTargetUserId = async (): Promise<string | null> => {
      if (params.target_user_id) return String(params.target_user_id);
      if (params.target_phone) {
        const { data } = await admin
          .from('profiles')
          .select('user_id')
          .eq('phone', String(params.target_phone))
          .maybeSingle();
        return data?.user_id ?? null;
      }
      return null;
    };

    switch (operation) {
      case 'list_admins': {
        const { data, error } = await admin
          .from('user_roles')
          .select('user_id, role, created_at')
          .in('role', ['admin', 'super_admin'])
          .order('created_at', { ascending: false });
        if (error) return json(500, { error: (error instanceof Error ? error.message : String(error)) });

        const ids = (data ?? []).map((r) => r.user_id);
        const { data: profiles } = ids.length
          ? await admin.from('profiles').select('user_id, display_name, phone, avatar_url').in('user_id', ids)
          : { data: [] as any[] };

        const profileMap = new Map((profiles ?? []).map((p: any) => [p.user_id, p]));
        const merged = (data ?? []).map((r) => ({ ...r, profile: profileMap.get(r.user_id) ?? null }));
        return json(200, { data: merged, count: merged.length });
      }

      case 'grant_admin': {
        const targetId = await resolveTargetUserId();
        if (!targetId) return json(400, { error: '未找到目标用户（请提供 target_user_id 或 target_phone）' });

        const role = params.role === 'super_admin' ? 'super_admin' : 'admin';

        const { data, error } = await admin
          .from('user_roles')
          .upsert(
            { user_id: targetId, role, created_by: user.id },
            { onConflict: 'user_id,role' }
          )
          .select()
          .single();
        if (error) return json(500, { error: (error instanceof Error ? error.message : String(error)) });

        return json(200, { data, message: `已授予 ${role} 角色` });
      }

      case 'revoke_admin': {
        const targetId = await resolveTargetUserId();
        if (!targetId) return json(400, { error: '未找到目标用户' });
        if (targetId === user.id) return json(400, { error: '不能撤销自己的管理员权限' });

        const { error } = await admin
          .from('user_roles')
          .delete()
          .eq('user_id', targetId)
          .in('role', ['admin', 'super_admin']);
        if (error) return json(500, { error: (error instanceof Error ? error.message : String(error)) });

        return json(200, { message: '已撤销管理员权限' });
      }

      default:
        return json(400, { error: `未知操作: ${operation}` });
    }
  } catch (e) {
    console.error('[admin-team] error', e);
    return json(500, { error: e instanceof Error ? e.message : String(e) });
  }
});
