import { Body, Controller, Post, Req } from '@nestjs/common';
import { Request } from 'express';
import { AddOssDto } from './dtos/add-oss.dto';
import { frontDay, getUid } from 'api/utils/utils';
import { OssService } from '../../common/oss.service';
import { Roles } from 'api/utils/decorator';
import { RoleEnum } from 'api/utils/constants';
import { LessThan } from 'typeorm';
import { removeQiniuFile } from 'api/utils/oss';

@Controller('oss')
export class OssController {
  constructor(private ossService: OssService) {}

  @Post('add')
  add(@Req() req: Request, @Body() addOssDto: AddOssDto) {
    const uid = getUid(req);
    const { key, size } = addOssDto;
    return this.ossService.save({
      uid,
      key,
      size,
    });
  }

  @Post('clear')
  @Roles(RoleEnum.SuperAdmin)
  async clear() {
    const ossFiles = await this.ossService.findAll({
      btype: 0,
      createDate: LessThan(frontDay(1)),
    });
    ossFiles.forEach((item) => {
      removeQiniuFile(item.key).then((isDelete) => {
        if (isDelete) {
          this.ossService.delete(item.id);
        }
      });
    });
    return ossFiles;
  }
}
