import { Controller, Post, Get, Body, Query, Param, UseGuards, HttpCode, HttpStatus } from '@nestjs/common'
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth, ApiQuery } from '@nestjs/swagger'
import { AuthorizationApplicationService } from '@/application/services'
import {
  GrantCommunityCommand,
  GrantProvinceCompanyCommand,
  GrantCityCompanyCommand,
  GrantAuthProvinceCompanyCommand,
  GrantAuthCityCompanyCommand,
  RevokeAuthorizationCommand,
} from '@/application/commands'
import {
  GrantCommunityDto,
  GrantProvinceCompanyDto,
  GrantCityCompanyDto,
  GrantAuthProvinceCompanyDto,
  GrantAuthCityCompanyDto,
  RevokeAuthorizationDto,
  QueryAuthorizationsDto,
} from '@/api/dto/request'
import { CurrentUser } from '@/shared/decorators'
import { JwtAuthGuard } from '@/shared/guards'
import { RoleType } from '@/domain/enums'

@ApiTags('Admin Authorization')
@Controller('admin/authorizations')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
export class AdminAuthorizationController {
  constructor(private readonly applicationService: AuthorizationApplicationService) {}

  @Get()
  @ApiOperation({ summary: '查询授权列表（管理员）' })
  @ApiQuery({ name: 'roleType', required: false, enum: RoleType })
  @ApiQuery({ name: 'keyword', required: false })
  @ApiQuery({ name: 'includeRevoked', required: false, type: Boolean })
  @ApiQuery({ name: 'page', required: false, type: Number })
  @ApiQuery({ name: 'limit', required: false, type: Number })
  @ApiResponse({ status: 200, description: '授权列表' })
  async queryAuthorizations(
    @Query() dto: QueryAuthorizationsDto,
  ): Promise<{
    items: Array<{
      id: string
      accountSequence: string
      nickname: string
      avatar: string | null
      roleType: RoleType
      regionName: string
      status: string
      benefitActive: boolean
      createdAt: Date
      authorizedAt: Date | null
      revokedAt: Date | null
      revokeReason: string | null
      officePhotoUrls: string[]
    }>
    total: number
    page: number
    limit: number
  }> {
    return this.applicationService.queryAuthorizations({
      roleType: dto.roleType,
      keyword: dto.keyword,
      includeRevoked: dto.includeRevoked,
      page: dto.page,
      limit: dto.limit,
    })
  }

  @Post(':id/revoke')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '撤销授权（管理员）' })
  @ApiResponse({ status: 200, description: '撤销成功' })
  async revokeAuthorization(
    @CurrentUser() user: { userId: string; accountSequence?: string },
    @Param('id') authorizationId: string,
    @Body() dto: RevokeAuthorizationDto,
  ): Promise<{ message: string }> {
    const command = new RevokeAuthorizationCommand(
      authorizationId,
      dto.reason,
      user.accountSequence || 'ADMIN',
    )
    await this.applicationService.revokeAuthorization(command)
    return { message: '授权已撤销' }
  }

  @Post('community')
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({ summary: '授权社区（管理员）' })
  @ApiResponse({ status: 201, description: '授权成功' })
  async grantCommunity(
    @CurrentUser() user: { userId: string; accountSequence?: string },
    @Body() dto: GrantCommunityDto,
  ): Promise<{ message: string }> {
    const command = new GrantCommunityCommand(
      dto.userId,
      dto.accountSequence,
      dto.communityName,
      user.userId,
      user.accountSequence || 'ADMIN',
      dto.skipAssessment ?? false,
    )
    await this.applicationService.grantCommunity(command)
    return { message: '社区授权成功' }
  }

  @Post('province-company')
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({ summary: '授权正式省公司（管理员）' })
  @ApiResponse({ status: 201, description: '授权成功' })
  async grantProvinceCompany(
    @CurrentUser() user: { userId: string; accountSequence?: string },
    @Body() dto: GrantProvinceCompanyDto,
  ): Promise<{ message: string }> {
    const command = new GrantProvinceCompanyCommand(
      dto.userId,
      dto.accountSequence,
      dto.provinceCode,
      dto.provinceName,
      user.userId,
      user.accountSequence || 'ADMIN',
      dto.skipAssessment ?? false,
    )
    await this.applicationService.grantProvinceCompany(command)
    return { message: '正式省公司授权成功' }
  }

  @Post('city-company')
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({ summary: '授权正式市公司（管理员）' })
  @ApiResponse({ status: 201, description: '授权成功' })
  async grantCityCompany(
    @CurrentUser() user: { userId: string; accountSequence?: string },
    @Body() dto: GrantCityCompanyDto,
  ): Promise<{ message: string }> {
    const command = new GrantCityCompanyCommand(
      dto.userId,
      dto.accountSequence,
      dto.cityCode,
      dto.cityName,
      user.userId,
      user.accountSequence || 'ADMIN',
      dto.skipAssessment ?? false,
    )
    await this.applicationService.grantCityCompany(command)
    return { message: '正式市公司授权成功' }
  }

  @Post('auth-province-company')
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({ summary: '授权省团队（管理员）' })
  @ApiResponse({ status: 201, description: '授权成功' })
  @ApiResponse({ status: 400, description: '验证失败（如团队内已存在相同省份授权）' })
  async grantAuthProvinceCompany(
    @CurrentUser() user: { userId: string; accountSequence?: string },
    @Body() dto: GrantAuthProvinceCompanyDto,
  ): Promise<{ message: string }> {
    const command = new GrantAuthProvinceCompanyCommand(
      dto.userId,
      dto.accountSequence,
      dto.provinceCode,
      dto.provinceName,
      user.userId,
      user.accountSequence || 'ADMIN',
      dto.skipAssessment ?? false,
    )
    await this.applicationService.grantAuthProvinceCompany(command)
    return { message: '省团队授权成功' }
  }

  @Post('auth-city-company')
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({ summary: '授权市团队（管理员）' })
  @ApiResponse({ status: 201, description: '授权成功' })
  @ApiResponse({ status: 400, description: '验证失败（如团队内已存在相同城市授权）' })
  async grantAuthCityCompany(
    @CurrentUser() user: { userId: string; accountSequence?: string },
    @Body() dto: GrantAuthCityCompanyDto,
  ): Promise<{ message: string }> {
    const command = new GrantAuthCityCompanyCommand(
      dto.userId,
      dto.accountSequence,
      dto.cityCode,
      dto.cityName,
      user.userId,
      user.accountSequence || 'ADMIN',
      dto.skipAssessment ?? false,
    )
    await this.applicationService.grantAuthCityCompany(command)
    return { message: '市团队授权成功' }
  }
}
