import {
  Controller,
  Get,
  Put,
  Patch,
  Body,
  UseGuards,
  Request,
  UnauthorizedException,
} from "@nestjs/common";
import { PreferencesService } from "./preferences.service";
import { UpdatePreferencesDto } from "./dto";
import { AuthGuard } from "../auth/guards/auth.guard";
import type { AuthenticatedRequest } from "../common/types/user.types";

/**
 * Controller for user preferences endpoints
 * All endpoints require authentication
 */
@Controller("users/me/preferences")
@UseGuards(AuthGuard)
export class PreferencesController {
  constructor(private readonly preferencesService: PreferencesService) {}

  /**
   * GET /api/users/me/preferences
   * Get current user's preferences
   */
  @Get()
  async getPreferences(@Request() req: AuthenticatedRequest) {
    const userId = req.user?.id;

    if (!userId) {
      throw new UnauthorizedException("Authentication required");
    }

    return this.preferencesService.getPreferences(userId);
  }

  /**
   * PUT /api/users/me/preferences
   * Full replace of current user's preferences
   */
  @Put()
  async updatePreferences(
    @Body() updatePreferencesDto: UpdatePreferencesDto,
    @Request() req: AuthenticatedRequest
  ) {
    const userId = req.user?.id;

    if (!userId) {
      throw new UnauthorizedException("Authentication required");
    }

    return this.preferencesService.updatePreferences(userId, updatePreferencesDto);
  }

  /**
   * PATCH /api/users/me/preferences
   * Partial update of current user's preferences
   */
  @Patch()
  async patchPreferences(
    @Body() updatePreferencesDto: UpdatePreferencesDto,
    @Request() req: AuthenticatedRequest
  ) {
    const userId = req.user?.id;

    if (!userId) {
      throw new UnauthorizedException("Authentication required");
    }

    return this.preferencesService.updatePreferences(userId, updatePreferencesDto);
  }
}
