-- =====================================================================================
-- RPC: rpc_admin_user_detail
-- Version: v1
-- Purpose: 管理后台用户详情（单个用户），返回完整资料+会员信息+地址
-- Security: SECURITY DEFINER + 固定 search_path + 入口鉴权（admin/analytics）
-- Depends:
--   - public.ak_users (auth_id, email, username, role, created_at, updated_at)
--   - public.ml_user_profiles (user_id, status, real_name, credit_score, verification_status, preferences, emergency_contact, service_areas)
--   - public.ml_user_addresses (user_id, receiver_name, receiver_phone, province, city, district, address_detail, is_default)
--   - public.ml_user_subscriptions (user_id, plan_id, status, start_date, end_date, next_billing_date, auto_renew)
--   - public.ml_subscription_plans (id, name, billing_period, price, features)
--   - public.get_current_user_role() (鉴权入口)
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_user_detail(
    p_user_id UUID
)
RETURNS JSONB
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
    v_user_detail JSONB;
BEGIN
    -- 1) 入口鉴权：仅允许 admin/analytics 角色调用
    IF get_current_user_role() NOT IN ('admin', 'analytics') THEN
        RAISE EXCEPTION 'Permission denied: required role admin or analytics';
    END IF;

    -- 2) 查询用户完整信息
    SELECT jsonb_build_object(
        'id', u.id,
        'auth_id', u.auth_id,
        'username', u.username,
        'email', u.email,
        'role', u.role,
        'profile_status', up.status,
        'real_name', up.real_name,
        'credit_score', up.credit_score,
        'verification_status', up.verification_status,
        'preferences', up.preferences,
        'emergency_contact', up.emergency_contact,
        'service_areas', up.service_areas,
        'created_at', u.created_at,
        'updated_at', u.updated_at,
        'balance', 0, -- 按要求固定返回 0
        'is_member', COALESCE(member_info.is_member, false),
        'member_info', member_info.subscription_detail,
        'addresses', address_info.addresses
    ) INTO v_user_detail
    FROM public.ak_users u
    LEFT JOIN public.ml_user_profiles up ON u.id = up.user_id
    LEFT JOIN LATERAL (
        SELECT
            true as is_member,
            jsonb_build_object(
                'plan_name', p.name,
                'plan_code', p.plan_code,
                'billing_period', p.billing_period,
                'price', p.price,
                'features', p.features,
                'status', s.status,
                'start_date', s.start_date,
                'end_date', s.end_date,
                'next_billing_date', s.next_billing_date,
                'auto_renew', s.auto_renew
            ) as subscription_detail
        FROM public.ml_user_subscriptions s
        JOIN public.ml_subscription_plans p ON s.plan_id = p.id
        WHERE s.user_id = u.auth_id
          AND s.status IN ('trial', 'active')
          AND (s.end_date IS NULL OR s.end_date >= now())
        ORDER BY s.end_date DESC NULLS FIRST
        LIMIT 1
    ) member_info ON true
    LEFT JOIN LATERAL (
        SELECT jsonb_agg(
            jsonb_build_object(
                'id', a.id,
                'receiver_name', a.receiver_name,
                'receiver_phone', a.receiver_phone,
                'province', a.province,
                'city', a.city,
                'district', a.district,
                'address_detail', a.address_detail,
                'postal_code', a.postal_code,
                'is_default', a.is_default,
                'label', a.label,
                'latitude', a.latitude,
                'longitude', a.longitude,
                'delivery_instructions', a.delivery_instructions,
                'business_hours', a.business_hours,
                'status', a.status,
                'created_at', a.created_at,
                'updated_at', a.updated_at
            ) ORDER BY a.is_default DESC, a.created_at DESC
        ) as addresses
        FROM public.ml_user_addresses a
        WHERE a.user_id = u.id
          AND a.status = 1
    ) address_info ON true
    WHERE u.id = p_user_id;

    -- 3) 用户不存在时返回 NULL
    IF v_user_detail IS NULL THEN
        RETURN NULL::jsonb;
    END IF;

    RETURN v_user_detail;
END;
$$;