import {
  Controller,
  Get,
  Param,
  Res,
  HttpStatus,
  NotFoundException,
} from '@nestjs/common';
import type { Response } from 'express';
import { ShortLinkService } from './short-link.service';

@Controller('s')
export class ShortLinkController {
  constructor(private readonly shortLinkService: ShortLinkService) {}

  /**
   * Redirige vers l'URL originale depuis un code court
   * @param code Le code court
   * @param res La réponse Express
   */
  @Get(':code')
  async redirect(@Param('code') code: string, @Res() res: Response) {
    try {
      const originalUrl = await this.shortLinkService.getOriginalUrl(code);
      return res.redirect(HttpStatus.FOUND, originalUrl);
    } catch (error) {
      if (error instanceof NotFoundException) {
        return res.status(HttpStatus.NOT_FOUND).json({
          statusCode: HttpStatus.NOT_FOUND,
          message: 'Short link not found',
        });
      }
      throw error;
    }
  }
}

