import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { AuthService } from 'src/auth/auth.service';
import { LoginDto, LoginLogoutDto, LoginRefreshDto } from 'src/auth/dto/login.dto';
import { SwitchEmpresaDto } from 'src/auth/dto/switch-empresa.dto';
import { GetUser } from 'src/auth/get-user.decorator';
import type { LoginUserInfo } from 'src/auth/dto/login.dto';

/**
 * Auth para la app móvil (Novasis Cobros). Reutiliza por completo `AuthService`.
 * Diferencia con la web: el refresh token vive más tiempo (sesión larga del
 * cobrador en ruta), configurable vía `MOBILE_JWT_REFRESH_EXPIRES_IN` (default 90d).
 */
@ApiTags('Mobile · Auth')
@Controller({ path: 'mobile/auth', version: '1' })
export class MobileAuthController {
  constructor(
    private readonly authService: AuthService,
    private readonly config: ConfigService,
  ) {}

  private getRefreshTtlSec(): number {
    const raw = Number(this.config.get('MOBILE_JWT_REFRESH_EXPIRES_IN'));
    return Number.isFinite(raw) && raw > 0 ? raw : 60 * 60 * 24 * 90; // 90 días
  }

  @Post('login')
  @ApiOperation({ summary: 'Login móvil (sesión larga). Devuelve tokens + datos de usuario' })
  login(@Body() dto: LoginDto) {
    return this.authService.login(dto, { refreshTtlSec: this.getRefreshTtlSec() });
  }

  @Post('refresh')
  @ApiOperation({ summary: 'Renovar tokens manteniendo la sesión larga móvil' })
  refresh(@Body() body: LoginRefreshDto) {
    return this.authService.refresh(body?.refresh_token, this.getRefreshTtlSec());
  }

  @Post('logout')
  @ApiOperation({ summary: 'Cerrar sesión (revoca el refresh token)' })
  logout(@Body() body: LoginLogoutDto) {
    return this.authService.logout(body?.refresh_token);
  }

  @Get('empresas')
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  @ApiOperation({ summary: 'Empresas accesibles por el usuario logueado (selector de empresa)' })
  empresas(@GetUser() user: LoginUserInfo) {
    return this.authService.getEmpresasAccesibles(user.id, user.empresa_id);
  }

  @Post('switch-empresa')
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  @ApiOperation({ summary: 'Cambiar la empresa activa de la sesión' })
  switchEmpresa(@Body() dto: SwitchEmpresaDto, @GetUser() user: LoginUserInfo) {
    return this.authService.switchEmpresa(user.id, dto.empresa_id, user.empresa_id);
  }
}
