import {
  Body,
  Controller,
  Get,
  Patch,
  Req,
  UnauthorizedException,
  UseGuards,
} from '@nestjs/common';
import type { Request } from 'express';

import { Roles } from '@/casl/roles.decorator';
import { RolesGuard } from '@/casl/roles.guard';
import { JwtAuthGuard } from '@/modules/auth/jwt-auth.guard';

import { UpdateNotificationSettingDto } from './dto/update-notification-setting.dto';
import { NotificationSettingsService } from './notification-settings.service';

const NOTIFICATION_SETTING_ROLES = [
  'admin',
  'ministry',
  'private_sector',
  'cdc_g-psf',
  'cdc',
  'cefp',
];

type AuthenticatedRequest = Request & {
  user?: {
    id?: number;
  };
};

@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(...NOTIFICATION_SETTING_ROLES)
@Controller('notification-settings')
export class NotificationSettingsController {
  constructor(
    private readonly notificationSettingsService: NotificationSettingsService,
  ) {}

  @Get('me')
  findMySetting(@Req() request: AuthenticatedRequest) {
    return this.notificationSettingsService.findMySetting(
      this.getCurrentUserId(request),
    );
  }

  @Patch('me')
  updateMySetting(
    @Req() request: AuthenticatedRequest,
    @Body() dto: UpdateNotificationSettingDto,
  ) {
    return this.notificationSettingsService.updateMySetting(
      this.getCurrentUserId(request),
      dto,
    );
  }

  private getCurrentUserId(request: AuthenticatedRequest): number {
    const userId = Number(request.user?.id);

    if (!Number.isInteger(userId) || userId <= 0) {
      throw new UnauthorizedException('Invalid authenticated user.');
    }

    return userId;
  }
}
