import {
  Controller,
  Get,
  Query,
  Req,
  Res,
  UseGuards,
} from '@nestjs/common';
import type { Response } from 'express';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { MyScheduleMasterService } from './services/my-schedule-master.service';
import { MyScheduleMasterExportService } from './services/my-schedule-master-export.service';

@Controller('my-schedule-master')
@UseGuards(JwtAuthGuard)
export class MyScheduleMasterController {
  constructor(
    private readonly data: MyScheduleMasterService,
    private readonly exporter: MyScheduleMasterExportService,
  ) {}

  // GET /my-schedule-master  → rows + counts + meta
  @Get()
  async list(@Query() q: any, @Req() req: any) {
    const userId: number = req.user.id;
    return this.data.list(userId, q);
  }

  // GET /my-schedule-master/export/excel
  @Get('export/excel')
  async excel(@Query() q: any, @Req() req: any, @Res() res: Response) {
    const userId: number = req.user.id;
    const buffer = await this.exporter.excel(userId, q);
    const filename = `my-audit-schedule-${new Date()
      .toISOString()
      .slice(0, 10)}.xlsx`;
    res.set({
      'Content-Type':
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'Content-Disposition': `attachment; filename="${filename}"`,
      'Content-Length': buffer.length,
    });
    res.end(buffer);
  }

  // GET /my-schedule-master/export/pdf
  @Get('export/pdf')
  async pdf(@Query() q: any, @Req() req: any, @Res() res: Response) {
    const userId: number = req.user.id;
    const buffer = await this.exporter.pdf(userId, q);
    const filename = `my-audit-schedule-${new Date()
      .toISOString()
      .slice(0, 10)}.pdf`;
    res.set({
      'Content-Type': 'application/pdf',
      'Content-Disposition': `attachment; filename="${filename}"`,
      'Content-Length': buffer.length,
    });
    res.end(buffer);
  }
}
