import {
  Controller,
  Get,
  Param,
  Query,
  UseGuards,
  Request,
  Res,
} from '@nestjs/common';
import { Response } from 'express';
import { ExportService } from './export.service';
import { JwtAuthGuard } from '../common/guards/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { Roles } from '../common/decorators/roles.decorator';

@Controller('school/export')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('school')
export class ExportController {
  constructor(private readonly exportService: ExportService) {}

  @Get('teachers')
  async exportTeachers(@Request() req: any, @Res() res: Response) {
    const buffer = await this.exportService.exportTeachers(req.user.tenantId);

    res.setHeader(
      'Content-Type',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
    res.setHeader(
      'Content-Disposition',
      `attachment; filename=teachers_${Date.now()}.xlsx`,
    );
    res.send(buffer);
  }

  @Get('students')
  async exportStudents(@Request() req: any, @Res() res: Response) {
    const buffer = await this.exportService.exportStudents(req.user.tenantId);

    res.setHeader(
      'Content-Type',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
    res.setHeader(
      'Content-Disposition',
      `attachment; filename=students_${Date.now()}.xlsx`,
    );
    res.send(buffer);
  }

  @Get('lessons')
  async exportLessons(@Request() req: any, @Res() res: Response) {
    const buffer = await this.exportService.exportLessons(req.user.tenantId);

    res.setHeader(
      'Content-Type',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
    res.setHeader(
      'Content-Disposition',
      `attachment; filename=lessons_${Date.now()}.xlsx`,
    );
    res.send(buffer);
  }

  @Get('growth-records')
  async exportGrowthRecords(
    @Request() req: any,
    @Query('studentId') studentId: string,
    @Res() res: Response,
  ) {
    const buffer = await this.exportService.exportGrowthRecords(
      req.user.tenantId,
      studentId ? +studentId : undefined,
    );

    res.setHeader(
      'Content-Type',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
    res.setHeader(
      'Content-Disposition',
      `attachment; filename=growth_records_${Date.now()}.xlsx`,
    );
    res.send(buffer);
  }
}
