import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Put,
  Query,
  Res,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ProductTagsService } from './product-tags.service';

@Controller('product-tags')
export class ProductTagsController {
  constructor(private readonly productTagsService: ProductTagsService) {}

  @Get(':tagType')
  list(
    @Param('tagType') tagType: string,
    @Query() query: Record<string, string>,
  ) {
    return this.productTagsService.list(tagType, query);
  }

  @Get(':tagType/export')
  async export(
    @Param('tagType') tagType: string,
    @Query() query: Record<string, string>,
    @Res() response: any,
  ) {
    const file = await this.productTagsService.exportFile(tagType, query);

    response.setHeader('Content-Type', file.mime);
    response.setHeader(
      'Content-Disposition',
      `attachment; filename="${file.fileName}"`,
    );
    response.send(Buffer.from(file.base64, 'base64'));
  }

  @Post(':tagType/import')
  @UseInterceptors(FileInterceptor('file'))
  import(@Param('tagType') tagType: string, @UploadedFile() file: any) {
    if (!file?.buffer || !file?.originalname) {
      return {
        totalRows: 0,
        created: 0,
        updated: 0,
        skipped: 1,
        errors: ['Import file is required.'],
      };
    }

    return this.productTagsService.importFile(tagType, file.originalname, file.buffer, file.mimetype);
  }

  @Post(':tagType/image')
  @UseInterceptors(FileInterceptor('file'))
  uploadImage(@Param('tagType') tagType: string, @UploadedFile() file: any) {
    if (!file?.buffer || !file?.originalname) {
      return {
        image: '',
        error: 'Image file is required.',
      };
    }

    return this.productTagsService.uploadImage(
      tagType,
      file.originalname,
      file.buffer,
      file.mimetype,
    );
  }

  @Post(':tagType')
  create(@Param('tagType') tagType: string, @Body() body: any) {
    return this.productTagsService.create(tagType, body);
  }

  @Put(':tagType/:id')
  update(
    @Param('tagType') tagType: string,
    @Param('id') id: string,
    @Body() body: any,
  ) {
    return this.productTagsService.update(tagType, id, body);
  }

  @Delete(':tagType/:id')
  delete(@Param('tagType') tagType: string, @Param('id') id: string) {
    return this.productTagsService.delete(tagType, id);
  }
}
