/**
 * 授权服务代理 — 自助申请照片查询
 * [2026-03-02] 纯新增：通过内部 HTTP 调用 authorization-service 获取自助申请照片
 *
 * === 架构 ===
 * admin-web → admin-service (本服务) → authorization-service /authorization/self-apply-photos
 * 复用 ReferralProxyService 的 axios 代理模式
 */

import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import axios, { AxiosInstance } from 'axios';
import { PrismaService } from '../infrastructure/persistence/prisma/prisma.service';

export interface SelfApplyPhotoItem {
  id: string;
  accountSequence: string;
  nickname: string;
  avatar: string | null;
  roleType: string;
  regionName: string;
  status: string;
  officePhotoUrls: string[];
  createdAt: string;
}

export interface SelfApplyPhotosResponse {
  items: SelfApplyPhotoItem[];
  total: number;
  page: number;
  limit: number;
}

@Injectable()
export class AuthorizationProxyService {
  private readonly logger = new Logger(AuthorizationProxyService.name);
  private readonly httpClient: AxiosInstance;

  constructor(
    private readonly configService: ConfigService,
    private readonly prisma: PrismaService,
  ) {
    const authorizationServiceUrl = this.configService.get<string>(
      'AUTHORIZATION_SERVICE_URL',
      'http://rwa-authorization-service:3009',
    );

    this.httpClient = axios.create({
      baseURL: authorizationServiceUrl,
      timeout: 30000,
    });

    this.logger.log(
      `AuthorizationProxyService initialized, authorization-service URL: ${authorizationServiceUrl}`,
    );
  }

  /**
   * 获取自助申请照片列表（含用户昵称/头像补充）
   */
  async getSelfApplyPhotos(params: {
    page?: number;
    limit?: number;
    roleType?: string;
  }): Promise<SelfApplyPhotosResponse> {
    const { page = 1, limit = 20, roleType } = params;

    try {
      // 1. 从 authorization-service 获取有照片的授权记录
      const queryParams = new URLSearchParams();
      queryParams.set('page', String(page));
      queryParams.set('limit', String(limit));
      if (roleType) {
        queryParams.set('roleType', roleType);
      }

      const url = `/api/v1/authorization/self-apply-photos?${queryParams.toString()}`;
      this.logger.debug(`[getSelfApplyPhotos] 请求: ${url}`);
      const response = await this.httpClient.get(url);
      // authorization-service 全局拦截器将响应包装为 {success, data, timestamp}
      // 实际数据在 response.data.data 中
      const raw = response.data;
      const data = raw?.data ?? raw;

      if (!data?.items?.length) {
        return { items: [], total: data?.total ?? 0, page, limit };
      }

      // 2. 批量查 user_query_view 补充 nickname + avatarUrl
      const accountSequences = data.items.map((item: any) => item.accountSequence);
      const users = await this.prisma.userQueryView.findMany({
        where: { accountSequence: { in: accountSequences } },
        select: { accountSequence: true, nickname: true, avatarUrl: true },
      });

      const userMap = new Map(
        users.map((u) => [u.accountSequence, { nickname: u.nickname, avatar: u.avatarUrl }]),
      );

      // 3. 合并数据
      const items: SelfApplyPhotoItem[] = data.items.map((item: any) => {
        const user = userMap.get(item.accountSequence);
        return {
          id: item.id,
          accountSequence: item.accountSequence,
          nickname: user?.nickname ?? item.accountSequence,
          avatar: user?.avatar ?? null,
          roleType: item.roleType,
          regionName: item.regionName,
          status: item.status,
          officePhotoUrls: item.officePhotoUrls ?? [],
          createdAt: item.createdAt,
        };
      });

      return { items, total: data.total, page, limit };
    } catch (error) {
      this.logger.error(`[getSelfApplyPhotos] 失败: ${error.message}`);
      return { items: [], total: 0, page, limit };
    }
  }
}
