import { Body, Controller, Post } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { ZodResponse } from 'nestjs-zod';
import { Public } from '../../common/decorators/public.decorator';
import { AuthService } from './auth.service';
import {
  ExchangeCodeRequestDto,
  ExchangeCodeResponseDto,
  MockLoginRequestDto,
  MockLoginResponseDto,
  RefreshTokenRequestDto,
  RefreshTokenResponseDto,
  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);
  }
}
