import {
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  Body,
  Param,
  Query,
  UseGuards,
  ParseUUIDPipe,
} from '@nestjs/common';
import { UserService } from './user.service';
import { CreateUserDto, UpdateUserDto, ResetPasswordDto } from './dto';
import { ClsService } from 'nestjs-cls';
import { IsOptional, IsUUID } from 'class-validator';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { PermissionGuard } from '../../auth/guards/permission.guard';
import { Permissions } from '../../auth/decorators/permissions.decorator';
import { AccessLevel, ModuleName } from '../../entities/role-permission.entity';
import { paginatedResponse, successResponse } from '../../common/responses/api-response';
import { PaginationDto } from '../../common/dto/pagination.dto';
import { Lookup } from '../../common/decorators/lookup.decorator';

/**
 * UserController — CRUD for users within a tenant.
 *
 * Per CLAUDE.md:
 * - Controller has ZERO tenant awareness
 * - No setTenantId() calls — CLS handles everything
 * - Never hardcode role checks — always use dynamic permission guard
 */
/**
 * DTO for the current user's self-update of workspace preferences.
 * Kept inline so it's obvious this isn't an admin-facing user edit.
 * Only `active_destination_id` is editable today; null = "All
 * destinations" (picker shows everything, no default filter).
 */
class UpdateMyPreferencesDto {
  @IsUUID()
  @IsOptional()
  active_destination_id?: string | null;
}

@Controller('users')
@UseGuards(JwtAuthGuard, PermissionGuard)
export class UserController {
  constructor(
    private readonly userService: UserService,
    private readonly cls: ClsService,
  ) {}

  /**
   * Update the current user's workspace preferences (top-bar picker
   * default). @Lookup bypasses the module-permission gate — every
   * authed user can set their own default, no SETTINGS:EDIT needed.
   */
  @Patch('me/preferences')
  @Lookup()
  async updateMyPreferences(@Body() dto: UpdateMyPreferencesDto) {
    const userId = this.cls.get<string>('user_id');
    const result = await this.userService.updatePreferences(userId, {
      active_destination_id: dto.active_destination_id ?? null,
    });
    return successResponse(result, 'Preferences updated');
  }

  @Get()
  @Permissions({ module: ModuleName.SETTINGS, accessLevel: AccessLevel.VIEW })
  async findAll(@Query() query: PaginationDto, @Query('reports_to') reportsTo?: string) {
    const { items, meta } = await this.userService.findAll({
      ...query,
      reports_to: reportsTo,
    });
    return paginatedResponse(items, meta, 'Users fetched successfully');
  }

  @Get('lookup')
  @Lookup()
  async lookup() {
    const items = await this.userService.findAllForLookup();
    return successResponse(items, 'Users lookup');
  }

  @Get(':id')
  @Permissions({ module: ModuleName.SETTINGS, accessLevel: AccessLevel.VIEW })
  async findById(@Param('id', ParseUUIDPipe) id: string) {
    const data = await this.userService.findById(id);
    return successResponse(data, 'User fetched successfully');
  }

  @Post()
  @Permissions({ module: ModuleName.SETTINGS, accessLevel: AccessLevel.CREATE })
  async create(@Body() dto: CreateUserDto) {
    const result = await this.userService.create(dto);
    return successResponse(result, result.message);
  }

  @Patch(':id')
  @Permissions({ module: ModuleName.SETTINGS, accessLevel: AccessLevel.EDIT })
  async update(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateUserDto) {
    const result = await this.userService.update(id, dto);
    return successResponse(result, result.message);
  }

  @Patch(':id/toggle-status')
  @Permissions({ module: ModuleName.SETTINGS, accessLevel: AccessLevel.EDIT })
  async toggleStatus(@Param('id', ParseUUIDPipe) id: string) {
    const result = await this.userService.toggleStatus(id);
    return successResponse(result, result.message);
  }

  @Patch(':id/reset-password')
  @Permissions({ module: ModuleName.SETTINGS, accessLevel: AccessLevel.EDIT })
  async resetPassword(@Param('id', ParseUUIDPipe) id: string, @Body() dto: ResetPasswordDto) {
    const result = await this.userService.resetPassword(id, dto);
    return successResponse(result, result.message);
  }

  @Delete(':id')
  @Permissions({ module: ModuleName.SETTINGS, accessLevel: AccessLevel.DELETE })
  async remove(@Param('id', ParseUUIDPipe) id: string) {
    const result = await this.userService.remove(id);
    return successResponse(result, result.message);
  }
}
