import { Controller, Get, Query, Request, UseGuards } from '@nestjs/common';
import { DashboardService } from './dashboard.service';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import {
  AuthorizationService,
  CaslAction,
  SubjectName,
} from '../authorization';
import { RequirePermission } from '../auth/decorators/permission.decorator';
import { DashboardGanttQueryDto, DashboardPeriodQueryDto } from './dto/dashboard-query.dto';

interface RequestUser {
  id: number;
  username: string;
  permissions: string[];
  isSuperAdmin: boolean;
}

@UseGuards(JwtAuthGuard)
@RequirePermission('dashboard:view')
@Controller('dashboard')
export class DashboardController {
  constructor(
    private service: DashboardService,
    private readonly authService: AuthorizationService,
  ) {}

  private canManageAllDashboard(req: { user: RequestUser }): boolean {
    const ability = this.authService.abilityForRequest(req);
    // Legacy: class:edit grants broad dashboard access
    return (
      ability.can(CaslAction.Manage, SubjectName.Dashboard) ||
      ability.can(CaslAction.Update, SubjectName.Class)
    );
  }

  private getAccessibleClassIds(req: { user: RequestUser }) {
    return this.service.getAccessibleClassIds(req.user.id, this.canManageAllDashboard(req));
  }

  @Get('stats')
  async getStats(@Request() req: { user: RequestUser }) {
    return this.service.getStats(await this.getAccessibleClassIds(req));
  }

  @Get('gantt')
  getGanttData(@Query() query: DashboardGanttQueryDto) {
    return this.service.getGanttData(query);
  }

  @Get('expense-stats')
  getExpenseStats(@Query() query: DashboardPeriodQueryDto) {
    return this.service.getExpenseStats(query.periodStart, query.periodEnd);
  }

  @Get('room-ranking')
  getRoomExpenseRanking(@Query() query: DashboardPeriodQueryDto) {
    return this.service.getRoomExpenseRanking(query.periodStart, query.periodEnd);
  }

  @Get('class-attendance-ranking')
  async getClassAttendanceRanking(@Request() req: { user: RequestUser }) {
    return this.service.getClassAttendanceRanking(await this.getAccessibleClassIds(req));
  }

  @Get('classroom-occupancy')
  getClassroomOccupancy() {
    return this.service.getClassroomOccupancy();
  }

  @Get('classroom-utilization')
  async getClassroomUtilization() {
    return this.service.getClassroomUtilizationStats();
  }
}
