import { Controller, Get, Post, Body, Patch, Param, Delete, UseGuards, Request, UnauthorizedException } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { ChangePasswordDto } from './dto/change-password.dto';

@Controller('users')
@UseGuards(AuthGuard('jwt'))
export class UsersController {
  constructor(private readonly usersService: UsersService) { }

  @Get('me/subordinates')
  getMySubordinates(@Request() req) {
    return this.usersService.getSubordinateIds(req.user.id).then(ids => {
        // Fetch full user objects for these IDs
        return this.usersService.findAllByIds(ids);
    });
  }

  @Post()
  create(@Request() req, @Body() createUserDto: CreateUserDto) {
    const creatorRole = req.user?.role;
    return this.usersService.create(createUserDto, creatorRole);
  }

  @Patch(':id/status')
  async updateStatus(@Request() req, @Param('id') id: string, @Body('status') status: 'PENDING' | 'APPROVED' | 'REJECTED') {
    if (req.user?.role !== 'ADMIN' && req.user?.role !== 'GENERAL_MANAGER') {
      throw new Error('Unauthorized to approve/reject users');
    }
    return this.usersService.updateStatus(id, status);
  }


  @Get()
  findAll() {
    return this.usersService.findAll();
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.usersService.findOne(id);
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
    return this.usersService.update(id, updateUserDto);
  }

  @Post('me/change-password')
  async changePassword(@Request() req, @Body() changePasswordDto: ChangePasswordDto) {
    try {
      await this.usersService.changePassword(req.user.id, changePasswordDto.oldPassword, changePasswordDto.newPassword);
      return { message: 'Password updated successfully' };
    } catch (error) {
      throw new UnauthorizedException(error.message);
    }
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.usersService.remove(id);
  }
}
