import {
  Controller,
  Get,
  Post,
  Put,
  Body,
  Param,
  UseGuards,
  Req,
  Query,
  UseInterceptors,
  UploadedFile,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { multerConfig } from '../common/config/multer.config';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { Roles, Role } from '../common/decorators/roles.decorator';

// ─── Import des types seulement ─────────────────────────────────────
import type {
  CreateUserDto,
  UpdateUserDto,
  UpdateProfileDto,
  CreateCareerHistoryDto,
  UsersFilters,
} from './users.service';

// ─── Import de la classe de service (valeur) ────────────────────────
import { UsersService } from './users.service';

@Controller('users')
@UseGuards(JwtAuthGuard)
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  // ─── Liste des utilisateurs (admin/manager) ──────────────────────────────────
  @Get()
  @UseGuards(RolesGuard)
  @Roles(Role.DIRECTOR, Role.AGENCY_MANAGER)
  findAll(
    @Query('search') search?: string,
    @Query('role') role?: string,
    @Query('team_id') team_id?: string,
    @Query('agency_id') agency_id?: string,
    @Query('is_active') is_active?: string,
    @Query('page') page?: string,
    @Query('limit') limit?: string,
  ) {
    const filters: UsersFilters = {
      search,
      role,
      team_id: team_id ? +team_id : undefined,
      agency_id: agency_id ? +agency_id : undefined,
      is_active: is_active !== undefined ? is_active === 'true' : undefined,
      page: page ? +page : 1,
      limit: limit ? +limit : 20,
    };
    return this.usersService.findAll(filters);
  }

  // ─── Stats RH ───────────────────────────────────────────────────────────────
  @Get('stats')
  @UseGuards(RolesGuard)
  @Roles(Role.DIRECTOR, Role.AGENCY_MANAGER)
  getStats() {
    return this.usersService.getStats();
  }

  // ─── Mon profil ─────────────────────────────────────────────────────────────
  @Get('me')
  getMe(@Req() req) {
    return this.usersService.findOne(req.user.id);
  }

  // ─── Mon profil RH ──────────────────────────────────────────────────────────
  @Get('me/profile')
  getMyProfile(@Req() req) {
    return this.usersService.getProfile(req.user.id);
  }

  // ─── Mettre à jour mon profil RH ────────────────────────────────────────────
  @Put('me/profile')
  updateMyProfile(@Req() req, @Body() dto: UpdateProfileDto) {
    return this.usersService.updateProfile(req.user.id, dto);
  }

  // ─── Upload de mon avatar ───────────────────────────────────────────────────
  @Put('me/avatar')
  @UseInterceptors(FileInterceptor('avatar', multerConfig))
  uploadMyAvatar(@Req() req, @UploadedFile() file: Express.Multer.File) {
    return this.usersService.updateAvatar(req.user.id, file.filename);
  }

  // ─── Mon historique de carrière ─────────────────────────────────────────────
  @Get('me/career')
  getMyCareer(@Req() req) {
    return this.usersService.getCareerHistory(req.user.id);
  }

  // ─── Détail d'un utilisateur ────────────────────────────────────────────────
  @Get(':id')
  @UseGuards(RolesGuard)
  @Roles(Role.DIRECTOR, Role.AGENCY_MANAGER, Role.TEAM_LEAD)
  findOne(@Param('id') id: string) {
    return this.usersService.findOne(+id);
  }

  // ─── Créer un utilisateur ───────────────────────────────────────────────────
  @Post()
  @UseGuards(RolesGuard)
  @Roles(Role.DIRECTOR, Role.AGENCY_MANAGER)
  create(@Body() dto: CreateUserDto) {
    return this.usersService.create(dto);
  }

  // ─── Mettre à jour un utilisateur ───────────────────────────────────────────
  @Put(':id')
  @UseGuards(RolesGuard)
  @Roles(Role.DIRECTOR, Role.AGENCY_MANAGER)
  update(@Param('id') id: string, @Body() dto: UpdateUserDto) {
    return this.usersService.update(+id, dto);
  }

  // ─── Activer/désactiver un utilisateur ──────────────────────────────────────
  @Put(':id/toggle-active')
  @UseGuards(RolesGuard)
  @Roles(Role.DIRECTOR)
  toggleActive(@Param('id') id: string) {
    return this.usersService.toggleActive(+id);
  }

  // ─── Profil RH d'un utilisateur ─────────────────────────────────────────────
  @Get(':id/profile')
  @UseGuards(RolesGuard)
  @Roles(Role.DIRECTOR, Role.AGENCY_MANAGER)
  getProfile(@Param('id') id: string) {
    return this.usersService.getProfile(+id);
  }

  // ─── Mettre à jour profil RH d'un utilisateur ───────────────────────────────
  @Put(':id/profile')
  @UseGuards(RolesGuard)
  @Roles(Role.DIRECTOR, Role.AGENCY_MANAGER)
  updateProfile(@Param('id') id: string, @Body() dto: UpdateProfileDto) {
    return this.usersService.updateProfile(+id, dto);
  }

  // ─── Historique de carrière ─────────────────────────────────────────────────
  @Get(':id/career')
  @UseGuards(RolesGuard)
  @Roles(Role.DIRECTOR, Role.AGENCY_MANAGER)
  getCareerHistory(@Param('id') id: string) {
    return this.usersService.getCareerHistory(+id);
  }

  // ─── Ajouter un événement de carrière ───────────────────────────────────────
  @Post(':id/career')
  @UseGuards(RolesGuard)
  @Roles(Role.DIRECTOR, Role.AGENCY_MANAGER)
  addCareerEvent(
    @Req() req,
    @Param('id') id: string,
    @Body() dto: Omit<CreateCareerHistoryDto, 'user_id'>,
  ) {
    return this.usersService.addCareerEvent({ ...dto, user_id: +id }, req.user);
  }
}