import {
  BadRequestException,
  Body,
  Controller,
  Post,
  Req,
} from '@nestjs/common';
import { ShortUrlService } from 'api/common/short-url.service';
import { GenerateUrlDto } from './dtos/generate-url.dto';
import { getUid } from 'api/utils/utils';
import { Request } from 'express';
import ShortUniqueId from 'short-unique-id';
import { CustomUrlDto } from './dtos/custom-url.dto';

const { randomUUID } = new ShortUniqueId({ length: 10 });

@Controller('shorturl')
export class ShortUrlController {
  constructor(private shortUrlService: ShortUrlService) {}

  @Post('generate')
  async generateAndQueryUrl(
    @Req() req: Request,
    @Body() generateUrlDto: GenerateUrlDto,
  ) {
    const uid = getUid(req);
    const { url } = generateUrlDto;
    const shortUrl = await this.shortUrlService.find({
      uid,
      originUrl: url,
    });
    if (shortUrl) {
      return shortUrl.shortId;
    }
    let shortUrlId = randomUUID();
    const hasShortUrl = await this.shortUrlService.find({
      shortId: shortUrlId,
    });
    if (hasShortUrl) {
      shortUrlId = randomUUID();
    }
    const result = await this.shortUrlService.save({
      uid,
      originUrl: url,
      shortId: shortUrlId,
    });
    return result.shortId;
  }

  @Post('custom')
  async customUrl(@Req() req: Request, @Body() customUrlDto: CustomUrlDto) {
    const uid = getUid(req);
    const { url, name } = customUrlDto;
    const shortUrl = await this.shortUrlService.find({
      uid,
      originUrl: url,
    });
    const hasShortUrl = await this.shortUrlService.find({
      shortId: name,
    });
    if (hasShortUrl) {
      throw new BadRequestException('自定义名称已占用,请换一个');
    }
    if (shortUrl) {
      await this.shortUrlService.delete(shortUrl.id);
    }
    return await this.shortUrlService.save({
      uid,
      originUrl: url,
      shortId: name,
    });
  }
}
