import { Body, Controller, Get, Post } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { ZodResponse } from 'nestjs-zod';
import type { AccessTokenPayload } from '@pac/types';
import { Public } from '../../common/decorators/public.decorator';
import { CurrentUser } from '../../common/decorators/current-user.decorator';
import {
  TenantScope,
  TenantScopeContext,
} from '../../common/decorators/tenant-scope.decorator';
import { AuthService } from './auth.service';
import {
  ExchangeCodeRequestDto,
  ExchangeCodeResponseDto,
  MockLoginRequestDto,
  MockLoginResponseDto,
  MockUsersResponseDto,
  RefreshTokenRequestDto,
  RefreshTokenResponseDto,
  SessionResponseDto,
  TokenExchangeRequestDto,
  TokenExchangeResponseDto,
} from './dto/auth.dto';

@ApiTags('auth')
@Controller('auth')
export class AuthController {
  constructor(private readonly auth: AuthService) {}

  @Public()
  @Post('token')
  @ZodResponse({ status: 200, type: TokenExchangeResponseDto })
  @ApiOperation({
    summary:
      'Token Exchange — host backend trades appId+appSecret+user for an accessToken + one-time code',
  })
  exchangeToken(@Body() dto: TokenExchangeRequestDto) {
    return this.auth.exchangeToken(dto);
  }

  @Public()
  @Post('exchange-code')
  @ZodResponse({ status: 200, type: ExchangeCodeResponseDto })
  @ApiOperation({ summary: 'Exchange a one-time code (from iframe URL) for the accessToken' })
  exchangeCode(@Body() dto: ExchangeCodeRequestDto) {
    return this.auth.exchangeCode(dto.code);
  }

  @Public()
  @Post('refresh')
  @ZodResponse({ status: 200, type: RefreshTokenResponseDto })
  @ApiOperation({ summary: 'Refresh the accessToken before expiry' })
  refresh(@Body() dto: RefreshTokenRequestDto) {
    return this.auth.refresh(dto.refreshToken);
  }

  @Public()
  @Post('mock-login')
  @ZodResponse({ status: 200, type: MockLoginResponseDto })
  @ApiOperation({
    summary:
      'Mock login(开发 / 试部署用,env 门控)— 按 { tenant, role } 预制 user payload 直产 JWT',
    description:
      'env: PAC_ENABLE_MOCK_LOGIN=true 强开 / =false 强关;不设按 NODE_ENV(prod 默认关)。' +
      '生产真 host SSO 接入后,把 env 设 false 或删该 endpoint。',
  })
  mockLogin(@Body() dto: MockLoginRequestDto) {
    return this.auth.mockLogin(dto);
  }

  @Public()
  @Get('mock-users')
  @ZodResponse({ status: 200, type: MockUsersResponseDto })
  @ApiOperation({
    summary: '客服花名册(开发 / 试部署用)— 给"快速登录"对话框选人',
    description:
      '派生自 data/jvs-dw/users.json(回访表 · 近 12 月在岗)。mock 登录禁用时返空数组。',
  })
  mockUsers() {
    return { users: this.auth.listMockUsers() };
  }

  @Get('session')
  @ApiBearerAuth('accessToken')
  @ZodResponse({ status: 200, type: SessionResponseDto })
  @ApiOperation({
    summary:
      '当前会话视图 — 把 JWT.orgScope 展开成 clinicIds/sourceUnits 返给前端(设计 B:JWT 只装通用 orgScope,前端展不开)',
  })
  async session(
    @CurrentUser() user: AccessTokenPayload,
    @TenantScope() scope: TenantScopeContext,
  ) {
    return {
      sub: user.sub,
      hostId: user.hostId,
      tenantId: user.tenantId,
      role: user.role,
      permissions: user.permissions,
      orgScope: user.orgScope,
      clinicIds: scope.clinicIds, // 拦截器已按 host org 树展开
      sourceUnits: scope.sourceUnits,
      ...(user.dictionary ? { dictionary: user.dictionary } : {}),
      // 宿主动作跳转模板 —— 前端"新建预约"等按钮据此打开宿主页(缺失=不渲染/不跳)
      actionUrls: await this.auth.getActionUrls(user.hostId),
    };
  }
}
