import {
  BadRequestException,
  Controller,
  Get,
  Param,
  Redirect,
} from '@nestjs/common';
import { ShortUrlService } from 'api/common/short-url.service';
import { SkipAuth } from 'api/utils/decorator';

@Controller('s')
export class ShortController {
  constructor(private shortUrlService: ShortUrlService) {}

  @Get(':key')
  @SkipAuth()
  @Redirect()
  async getUrl(@Param('key') key: string) {
    if (!key) {
      throw new BadRequestException('短链接不能为空');
    }
    const shortUrl = await this.shortUrlService.find({
      shortId: key,
    });
    this.shortUrlService.update(shortUrl.id, {
      count: shortUrl.count + 1,
    });
    if (!shortUrl) {
      throw new BadRequestException('链接不存在');
    }
    return {
      url: shortUrl.originUrl,
      statusCode: 302,
    };
  }
}
