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

@Controller('wheel-master')
export class WheelMasterController {
  constructor(private readonly wheelMasterService: WheelMasterService) {}

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

  @Get('filters/wheel-types')
  wheelTypes() {
    return this.wheelMasterService.getWheelTypeOptions();
  }

  @Get('filters/bearing-types')
  bearingTypes() {
    return this.wheelMasterService.getBearingTypeOptions();
  }

  @Get('export')
  async export(@Query() query: Record<string, string>, @Res() response: any) {
    const csv = await this.wheelMasterService.exportCsv(query);
    response.setHeader('Content-Type', 'text/csv; charset=utf-8');
    response.setHeader(
      'Content-Disposition',
      'attachment; filename="wheel-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.wheelMasterService.importFile(file.buffer);
  }

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

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

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