import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  UploadedFile,
  UseInterceptors,
  StreamableFile,
  Header,
} from '@nestjs/common';
import { FilesService } from './files.service';
import { UpdateFileDto } from './dto/update-file.dto';
import { FileInterceptor } from '@nestjs/platform-express';
import AvatarMulterOpions from 'src/common/upload/avatar';
import {
  AuthPayload,
  AuthTenant,
} from 'src/auth/decorators/auth.payload';
import { Public } from 'src/auth/decorators/public.auth';

@Controller('files')
export class FilesController {
  constructor(private readonly filesService: FilesService) { }

  @Post()
  @UseInterceptors(FileInterceptor('file', AvatarMulterOpions))
  uploadFile(
    @UploadedFile() file: Express.Multer.File,
    @AuthTenant() tenant: AuthPayload,
  ) {
    return this.filesService.create(file, tenant);
  }

  @Get('/:folder/:id')
  @Header('Cross-Origin-Opener-Policy', 'unsafe-none')
  @Header('Cross-Origin-Resource-Policy', 'cross-origin')
  @Public()
  findOne(
    @Param('folder') folder: string,
    @Param('id') id: string,
  ): StreamableFile {
    const file = this.filesService.getFile(folder, id);
    return new StreamableFile(file);
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() updateFileDto: UpdateFileDto) {
    return this.filesService.update(+id, updateFileDto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.filesService.remove(+id);
  }
}
