import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Patch,
  Post,
  Query,
  Res,
  UseGuards,
} from '@nestjs/common'
import { AuthGuard } from '@nestjs/passport'
import { Roles } from 'src/auth/decorators/roles.decorator'
import { RolesGuard } from 'src/auth/guards/roles.guard'
import { BootstrapTableRequestDto } from 'src/commons/dto/bootstrap-table-request.dto'
import { CreateCustomerDto } from './dto/create-customer.dto'
import { UpdateCustomerDto } from './dto/update-customer.dto'
import { CustomerService } from './customer.service'
import { ExportService } from 'src/export/export.service'
import { ExportQueryDto } from 'src/export/export.types'
import { CUSTOMER_COLUMNS, formatCustomerRows } from 'src/export/formatters/customer.formatter'
import { Response } from 'express';
import { exportFilename } from 'src/export/export.utils'

@Controller('customers')
@UseGuards(AuthGuard('jwt'), RolesGuard)
export class CustomerController {
  constructor(
    private readonly service: CustomerService,
    private readonly exportService: ExportService,
  ) { }

  @Post()
  @Roles('SUPER_ADMIN', 'HEAD_STORE', 'HEAD_OPS', 'FRONTLINER')
  create(@Body() dto: CreateCustomerDto) {
    return this.service.create(dto)
  }

  @Get()
  @Roles('SUPER_ADMIN', 'HEAD_STORE', 'HEAD_OPS', 'HEAD_FINANCE', 'FRONTLINER', 'STAKEHOLDERS')
  findAll(@Query() query: BootstrapTableRequestDto) {
    return this.service.findAll(query)
  }

  @Get('export')
  @Roles('SUPER_ADMIN', 'HEAD_FINANCE', 'ADMIN_FINANCE', 'STAKEHOLDERS') // Fix later
  async export(
    @Query() query: ExportQueryDto,
    @Res() res: Response,
  ) {
    const customers = await this.service.getCustomersForExport(query);

    await this.exportService.export(
      {
        filename: exportFilename('customers'),
        sheetName: 'Customers',
        columns: CUSTOMER_COLUMNS,
        data: formatCustomerRows(customers),
        format: query.format,
      },
      res,
    );
  }

  @Get(':id')
  @Roles('SUPER_ADMIN', 'HEAD_STORE', 'HEAD_OPS', 'HEAD_FINANCE', 'FRONTLINER', 'STAKEHOLDERS')
  findOne(@Param('id') id: string) {
    return this.service.findOne(id)
  }

  @Patch(':id')
  @Roles('SUPER_ADMIN', 'HEAD_STORE', 'HEAD_OPS', 'FRONTLINER')
  update(@Param('id') id: string, @Body() dto: UpdateCustomerDto) {
    return this.service.update(id, dto)
  }

  @Delete(':id')
  @Roles('SUPER_ADMIN')
  remove(@Param('id') id: string) {
    return this.service.remove(id)
  }
}