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

@Controller('holder-master')
export class HolderMasterController {
  constructor(private readonly holderMasterService: HolderMasterService) {}

  @Get()
  list(@Query() query: Record<string, string>) {
    return this.holderMasterService.list(query);
  }

  @Get('filters/inches')
  inches() {
    return this.holderMasterService.getInchOptions();
  }

  @Get('filters/body-codes')
  bodyCodes() {
    return this.holderMasterService.getBodyCodeOptions();
  }

  @Get('export')
  async export(@Query() query: Record<string, string>, @Res() response: any) {
    const csv = await this.holderMasterService.exportCsv(query);

    response.setHeader('Content-Type', 'text/csv; charset=utf-8');
    response.setHeader(
      'Content-Disposition',
      'attachment; filename="holder-master.csv"',
    );
    response.send(csv);
  }

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

    return this.holderMasterService.importFile(file.buffer);
  }

  @Post()
  create(@Body() body: any) {
    return this.holderMasterService.create(body);
  }

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

  @Delete(':id')
  delete(@Param('id') id: string) {
    return this.holderMasterService.delete(id);
  }
}
