import { Body, Controller, ForbiddenException, Get, HttpCode, Put, Query } from '@nestjs/common';
import { ClsService } from 'nestjs-cls';
import { createZodDto } from 'nestjs-zod';
import {
  SaveMetaPositivacaoBodySchema,
  type RepDashboard,
  type SupervisorDashboard,
  type ManagerDashboard,
  type SaveMetaPositivacaoBody,
} from '@sar/api-interface';
import type { WorkspaceClsStore } from '../workspace/workspace.types';
import { DashboardService } from './dashboard.service';

class SaveMetaPositivacaoDto extends createZodDto(SaveMetaPositivacaoBodySchema) {}

@Controller({ path: 'dashboard' })
export class DashboardController {
  constructor(
    private readonly dashboard: DashboardService,
    private readonly cls: ClsService<WorkspaceClsStore>,
  ) {}

  // PGD-AUTHZ: dashboards gerenciais agregam dados da empresa toda (faturamento,
  // ranking de todos os reps) — rep não pode acessá-los.
  private assertGestor(): void {
    const role = this.cls.get('role') ?? 'rep';
    if (role === 'rep') {
      throw new ForbiddenException('Apenas supervisores e gerentes podem acessar este painel');
    }
  }

  @Get('rep')
  repDashboard(): Promise<RepDashboard> {
    return this.dashboard.repDashboard(this.cls.get('userId') ?? '');
  }

  @Get('supervisor')
  supervisorDashboard(): Promise<SupervisorDashboard> {
    this.assertGestor();
    return this.dashboard.supervisorDashboard();
  }

  @Put('manager/meta-positivacao-dia')
  @HttpCode(204)
  saveMetaPositivacaoDia(@Body() body: SaveMetaPositivacaoDto): Promise<void> {
    this.assertGestor();
    const parsed = SaveMetaPositivacaoBodySchema.parse(body) as SaveMetaPositivacaoBody;
    return this.dashboard.saveMetaPositivacaoDia(parsed.meta);
  }

  @Get('manager')
  managerDashboard(
    @Query('mes') mes?: string,
    @Query('ano') ano?: string,
  ): Promise<ManagerDashboard> {
    this.assertGestor();
    return this.dashboard.managerDashboard(
      mes ? parseInt(mes, 10) : undefined,
      ano ? parseInt(ano, 10) : undefined,
    );
  }
}
