import { Controller, Get, Param, Query, Res } from '@nestjs/common';
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { Response } from 'express';
import { RequirePermissions } from '@/common/auth/decorators';
import { ReportsService } from './reports.service';

@ApiTags('reports')
@ApiBearerAuth()
@Controller('reports')
export class ReportsController {
  constructor(private readonly reports: ReportsService) {}

  @Get('dashboard/:warehouseId') @RequirePermissions('reports.read') dashboard(@Param('warehouseId') warehouseId: string) { return this.reports.dashboard(warehouseId); }
  @Get('occupancy/:warehouseId') @RequirePermissions('reports.read') occupancy(@Param('warehouseId') warehouseId: string) { return this.reports.occupancy(warehouseId); }
  @Get('stock-aging/:warehouseId') @RequirePermissions('reports.read') aging(@Param('warehouseId') warehouseId: string, @Query('storerId') storerId?: string) { return this.reports.stockAging(warehouseId, storerId); }
  @Get('expiry/:warehouseId') @RequirePermissions('reports.read') expiry(@Param('warehouseId') warehouseId: string, @Query('days') days = '90', @Query('storerId') storerId?: string) { return this.reports.expiry(warehouseId, Number(days), storerId); }
  @Get('movements/:warehouseId') @RequirePermissions('reports.read') register(@Param('warehouseId') warehouseId: string, @Query('from') from: string, @Query('to') to: string, @Query('storerId') storerId?: string) { return this.reports.movementRegister(warehouseId, from, to, storerId); }
  @Get('productivity/:warehouseId') @RequirePermissions('reports.read') productivity(@Param('warehouseId') warehouseId: string, @Query('from') from: string, @Query('to') to: string) { return this.reports.productivity(warehouseId, from, to); }

  @Get('export/:report/:warehouseId') @RequirePermissions('reports.export')
  async export(@Param('report') report: string, @Param('warehouseId') warehouseId: string, @Query() q: Record<string, string>, @Res() res: Response) {
    let rows: Record<string, unknown>[];
    switch (report) {
      case 'stock-aging': rows = (await this.reports.stockAging(warehouseId, q.storerId)) as Record<string, unknown>[]; break;
      case 'expiry': rows = (await this.reports.expiry(warehouseId, Number(q.days ?? 90), q.storerId)) as Record<string, unknown>[]; break;
      case 'movements': rows = (await this.reports.movementRegister(warehouseId, q.from, q.to, q.storerId)) as Record<string, unknown>[]; break;
      case 'productivity': rows = (await this.reports.productivity(warehouseId, q.from, q.to)) as Record<string, unknown>[]; break;
      default: res.status(404).json({ statusCode: 404, message: `Unknown report ${report}` }); return;
    }
    res.setHeader('Content-Type', 'text/csv');
    res.setHeader('Content-Disposition', `attachment; filename="${report}.csv"`);
    res.send(this.reports.toCsv(rows));
  }
}
