import {
  Controller,
  Get,
  Patch,
  Body,
  Res,
  Req,
  UseGuards,
  HttpStatus,
  Param,
  BadRequestException,
  Post
} from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { toJsonResponse } from '../../common/response';
import { CommonGuard } from '../auth/guards/common.guard';
import { NotificationPreferencesService } from './notification-preferences.service';
import { UpdateWhatsAppPreferencesDto } from './dtos/update-whatsapp-preferences.dto';
import { UpdateNotificationPreferencesDto } from './dtos/update-notification-preferences.dto';
import { NotificationChannel } from '../../entities/user-notification-preferences.entity';
import { AdminGuard } from '../auth/guards/admin.guard';

@ApiTags('notification-preferences')
@Controller('notification-preferences')
export class NotificationPreferencesController {
  constructor(private readonly notificationPreferencesService: NotificationPreferencesService,) { }

  @UseGuards(CommonGuard)
  @Get()
  async getPreferences(@Req() req: any, @Res() response: any) {
    try {
      const userId = req.user?.id;
      const data = await this.notificationPreferencesService.getPreferences(userId);
      return response.status(HttpStatus.OK).json(data);
    } catch (error) {
      const status = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
      return response.status(status).json(toJsonResponse(status, error.message));
    }
  }

  @ApiBearerAuth('access-token')
  @UseGuards(CommonGuard)
  @Patch(':channel')
  async updatePreferences(@Req() req: any, @Param() param: any, @Body() body: UpdateNotificationPreferencesDto, @Res() response: any,) {
    try {

      await this.notificationPreferencesService.updatePreferences(req.user, param.channel, body);
      return response.status(HttpStatus.CREATED).json();
    } catch (error) {
      const status = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
      return response.status(status).json(toJsonResponse(status, error.message));
    }
  }

  @UseGuards(CommonGuard)
  @Post("script")
  async updateScriptPreferences(@Req() req: any, @Res() response: any,) {
    try {
      await this.notificationPreferencesService.script();
      return response.status(HttpStatus.CREATED).json();
    } catch (error) {
      const status = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
      return response.status(status).json(toJsonResponse(status, error.message));
    }
  }
}

