import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  UsePipes,
  ValidationPipe,
  Res,
  NotFoundException,
  BadRequestException,
  HttpStatus,
  Query,
  UseGuards,
} from '@nestjs/common';
import { NotificationsService } from './notifications.service';
import { CreateNotificationDto } from './dto/create-notification.dto';
import { UpdateNotificationDto } from './dto/update-notification.dto';
import {
  errorResponse,
  successResponse,
  validationErrorMessage,
} from 'src/common/errors/response-config';
import { Response as ExpressResponse } from 'express';
import { lan } from 'src/lan';
import { InjectRepository } from '@nestjs/typeorm';
import { ApiLog } from 'src/api-logs/entities/api-log.entity';
import { Repository } from 'typeorm';
import { saveError } from 'src/api-logs/api-error-log';
import { AppUser } from 'src/app_users/entities/app_user.entity';
import { AuthMiddleware } from 'src/common/middleware/auth.middleware';

@Controller('notifications')
@UseGuards(AuthMiddleware)
export class NotificationsController {
  constructor(
    private readonly notificationsService: NotificationsService,
    @InjectRepository(ApiLog)
    private readonly apiLogRepository: Repository<ApiLog>,
  ) {}

  @Post()
  @UsePipes(
    new ValidationPipe({
      exceptionFactory: validationErrorMessage,
      transform: true,
      transformOptions: {
        enableImplicitConversion: true,
      },
    }),
  )
  async create(
    @Body() createNotificationDto: CreateNotificationDto,
    @Res() res: ExpressResponse,
  ) {
    try {
      await this.notificationsService.create(createNotificationDto);
      res.send(successResponse(201, lan('common.request_submitted')));
    } catch (error) {
      saveError(error, this.apiLogRepository);
      if (
        error instanceof NotFoundException ||
        error instanceof BadRequestException
      ) {
        res
          .status(HttpStatus.BAD_REQUEST)
          .send(errorResponse(400, error.message));
      } else {
        res
          .status(HttpStatus.INTERNAL_SERVER_ERROR)
          .send(errorResponse(500, lan('common.internal_server_error'), error));
      }
    }
  }

  @Get()
  async findAll(
    @Query('take') take: number,
    @Query('skip') skip: number,
    @Res() res: ExpressResponse,
  ) {
    try {
      const notification = await this.notificationsService.findAll(take, skip);
      res
        .status(HttpStatus.OK)
        .send(
          successResponse(
            200,
            lan('common.data_retrieved_successfully'),
            notification,
          ),
        );
    } catch (error) {
      res
        .status(HttpStatus.INTERNAL_SERVER_ERROR)
        .send(errorResponse(500, lan('common.internal_server_error'), error));

      saveError(error, this.apiLogRepository);
    }
  }

  @Get(':id')
  async findUsersNotification(
    @Param('id') id: string,
    @Query('take') take: number,
    @Query('skip') skip: number,
    @Res() res: ExpressResponse,
  ) {
    try {
      const UserNotification =
        await this.notificationsService.findUserNotification(id, take, skip);

      res
        .status(HttpStatus.OK)
        .send(
          successResponse(
            200,
            lan('common.data_retrieved_successfully'),
            UserNotification,
          ),
        );
    } catch (error) {}
  }
}
