import {
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  Put,
  Body,
  Param,
  UseGuards,
  ParseUUIDPipe,
} from '@nestjs/common';
import { UserDepartmentsService } from './user-departments.service';
import {
  AddUserDepartmentDto,
  UpdateUserDepartmentDto,
} from './dto';
import { PermissionsGuard } from '../auth/guards/permissions.guard';
import { RequirePermissions } from '@common/decorators/permissions.decorator';
import { Auditable, Sensitive, Financial } from '@core/observability/audit/decorators/auditable.decorator';

@Controller('users/:userId/departments')
export class UserDepartmentsController {
  constructor(private readonly userDepartmentsService: UserDepartmentsService) {}

  /**
   * 获取用户的所有部门归属
   * Scope: organization - 只能查看本组织用户的部门归属
   */
  @Get()
  @RequirePermissions('user:read')
  async getUserDepartments(@Param('userId', ParseUUIDPipe) userId: string) {
    return this.userDepartmentsService.getUserDepartments(userId);
  }

  /**
   * 添加用户部门归属
   * Scope: organization - 只能为本组织用户添加部门归属
   */
  @Post()
  @Auditable()
  @Sensitive()
  @RequirePermissions('user:update')
  async addUserDepartment(
    @Param('userId', ParseUUIDPipe) userId: string,
    @Body() dto: AddUserDepartmentDto,
  ) {
    return this.userDepartmentsService.addUserDepartment(userId, dto);
  }

  /**
   * 更新用户在指定部门的归属信息
   * Scope: organization - 只能更新本组织用户的部门归属
   */
  @Patch(':departmentId')
  @Auditable()
  @Sensitive()
  @RequirePermissions('user:update')
  async updateUserDepartment(
    @Param('userId', ParseUUIDPipe) userId: string,
    @Param('departmentId', ParseUUIDPipe) departmentId: string,
    @Body() dto: UpdateUserDepartmentDto,
  ) {
    return this.userDepartmentsService.updateUserDepartment(userId, departmentId, dto);
  }

  /**
   * 设置主部门
   * Scope: organization - 只能设置本组织用户的主部门
   */
  @Put(':departmentId/primary')
  @Auditable()
  @Sensitive()
  @RequirePermissions('user:update')
  async setPrimaryDepartment(
    @Param('userId', ParseUUIDPipe) userId: string,
    @Param('departmentId', ParseUUIDPipe) departmentId: string,
  ) {
    return this.userDepartmentsService.setPrimaryDepartment(userId, departmentId);
  }

  /**
   * 移除用户部门归属
   * Scope: organization - 只能移除本组织用户的部门归属
   */
  @Delete(':departmentId')
  @Auditable()
  @Sensitive()
  @RequirePermissions('user:update')
  async removeUserDepartment(
    @Param('userId', ParseUUIDPipe) userId: string,
    @Param('departmentId', ParseUUIDPipe) departmentId: string,
  ) {
    return this.userDepartmentsService.removeUserDepartment(userId, departmentId);
  }
}

