import {
  Body,
  Controller,
  Get,
  NotFoundException,
  Put,
  UseGuards,
} from '@nestjs/common';
import { OidcAuthGuard } from '../../../../libs/auth/src';
import type { AuthenticatedUser } from '../../../../libs/auth/src';
import {
  UsersService,
  UserPreferencesService,
} from '../../../../libs/users/src';
import type {
  UpdateUserPreferenceDto,
  UserPreference,
} from '../../../../libs/users/src';
import { CurrentUser } from '../auth/current-user.decorator';

interface UserProfileResponse {
  id: string;
  displayName: string;
  email: string;
  createdAt: Date;
  updatedAt: Date;
}

@Controller('users/me')
@UseGuards(OidcAuthGuard)
export class UsersController {
  constructor(
    private readonly usersService: UsersService,
    private readonly preferencesService: UserPreferencesService,
  ) {}

  @Get()
  async me(
    @CurrentUser() currentUser: AuthenticatedUser,
  ): Promise<UserProfileResponse> {
    const user = await this.usersService.findById(currentUser.id);
    if (!user) throw new NotFoundException('User not found');
    return {
      id: user.id,
      displayName: user.displayName,
      email: user.email,
      createdAt: user.createdAt,
      updatedAt: user.updatedAt,
    };
  }

  @Get('preferences')
  getPreferences(
    @CurrentUser() currentUser: AuthenticatedUser,
  ): Promise<UserPreference> {
    return this.preferencesService.getOrDefault(currentUser.id);
  }

  @Put('preferences')
  updatePreferences(
    @CurrentUser() currentUser: AuthenticatedUser,
    @Body() dto: UpdateUserPreferenceDto,
  ): Promise<UserPreference> {
    return this.preferencesService.upsert(currentUser.id, dto);
  }
}
