/**
 * 自助申请照片内部 API
 * [2026-03-02] 纯新增：供 admin-service 调用，返回有照片的自助申请授权记录
 *
 * === 架构 ===
 * admin-web → admin-service → 本端点 → authorization_roles 表（源头数据）
 * 绕过 CDC 链路，直接读源头，保证 officePhotoUrls 100% 准确
 */

import { Controller, Get, Query, Logger } from '@nestjs/common'
import { ApiTags, ApiOperation, ApiQuery, ApiResponse } from '@nestjs/swagger'
import { PrismaService } from '@/infrastructure/persistence/prisma/prisma.service'
import { Prisma } from '@prisma/client'

interface SelfApplyPhotoRow {
  id: string
  account_sequence: string
  role_type: string
  region_name: string
  status: string
  office_photo_urls: string[]
  created_at: Date
}

@ApiTags('Internal Self-Apply Photos')
@Controller('authorization')
export class InternalSelfApplyPhotosController {
  private readonly logger = new Logger(InternalSelfApplyPhotosController.name)

  constructor(private readonly prisma: PrismaService) {}

  /**
   * 获取所有自助申请的授权记录（含办公室照片）
   * 自助申请的判断依据：officePhotoUrls 非空
   */
  @Get('self-apply-photos')
  @ApiOperation({ summary: '获取自助申请照片列表（内部 API）' })
  @ApiQuery({ name: 'page', required: false, type: Number, description: '页码，默认 1' })
  @ApiQuery({ name: 'limit', required: false, type: Number, description: '每页数量，默认 20' })
  @ApiQuery({ name: 'roleType', required: false, type: String, description: '授权类型筛选' })
  @ApiResponse({ status: 200, description: '自助申请照片列表' })
  async getSelfApplyPhotos(
    @Query('page') pageStr?: string,
    @Query('limit') limitStr?: string,
    @Query('roleType') roleType?: string,
  ) {
    const page = Math.max(1, Number(pageStr) || 1)
    const limit = Math.min(100, Math.max(1, Number(limitStr) || 20))
    const offset = (page - 1) * limit

    this.logger.debug(
      `[INTERNAL] getSelfApplyPhotos: page=${page}, limit=${limit}, roleType=${roleType || 'ALL'}`,
    )

    // 使用 raw SQL 查询，避免本地 Prisma client 类型不同步问题
    const roleTypeCondition = roleType
      ? Prisma.sql`AND role_type = ${roleType}`
      : Prisma.empty

    const [items, countResult] = await Promise.all([
      this.prisma.$queryRaw<SelfApplyPhotoRow[]>`
        SELECT id, account_sequence, role_type, region_name, status, office_photo_urls, created_at
        FROM authorization_roles
        WHERE office_photo_urls != '{}' AND deleted_at IS NULL
        ${roleTypeCondition}
        ORDER BY created_at DESC
        LIMIT ${limit} OFFSET ${offset}
      `,
      this.prisma.$queryRaw<[{ count: bigint }]>`
        SELECT COUNT(*)::bigint as count
        FROM authorization_roles
        WHERE office_photo_urls != '{}' AND deleted_at IS NULL
        ${roleTypeCondition}
      `,
    ])

    const total = Number(countResult[0]?.count ?? 0)

    return {
      items: items.map((item) => ({
        id: item.id,
        accountSequence: item.account_sequence,
        roleType: item.role_type,
        regionName: item.region_name,
        status: item.status,
        officePhotoUrls: item.office_photo_urls,
        createdAt: item.created_at instanceof Date ? item.created_at.toISOString() : String(item.created_at),
      })),
      total,
      page,
      limit,
    }
  }
}
