import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  UseGuards,
  UsePipes,
  ValidationPipe,
  Res,
  HttpStatus,
  Query,
  NotFoundException,
  BadRequestException,
  Headers,
  UseInterceptors,
  UploadedFile,
  UploadedFiles,
} from '@nestjs/common';
import { OffersService } from './offers.service';
import { CreateOfferDto } from './dto/create-offer.dto';
import { UpdateOfferDto } from './dto/update-offer.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { ApiLog } from 'src/api-logs/entities/api-log.entity';
import { Repository } from 'typeorm';
import { AuthMiddleware } from 'src/common/middleware/auth.middleware';
import {
  errorResponse,
  successResponse,
  validationErrorMessage,
} from 'src/common/errors/response-config';
import { Response as ExpressResponse } from 'express';
import { lan } from 'src/lan';
import { saveError } from 'src/api-logs/api-error-log';
import { imageConfig } from 'src/common/file upload/multer-config';
import {
  FileFieldsInterceptor,
  FileInterceptor,
} from '@nestjs/platform-express';
import { limits } from 'src/common/file upload/multer-config-helper';
import { FileValidationInterceptor } from 'src/common/file upload/ValidationInterceptor';

@Controller('offers')
export class OffersController {
  constructor(
    private readonly offersService: OffersService,
    @InjectRepository(ApiLog)
    private readonly apiLogRepository: Repository<ApiLog>,
  ) {}

  @Post()
  @UseGuards(AuthMiddleware)
  @UseInterceptors(
    FileFieldsInterceptor([{ name: 'banner', maxCount: 1 }], imageConfig),
    FileValidationInterceptor,
  )
  @UsePipes(
    new ValidationPipe({
      exceptionFactory: validationErrorMessage,
      transform: true,
      transformOptions: {
        enableImplicitConversion: true,
      },
    }),
  )
  async create(
    @Body() createOfferDto: CreateOfferDto,
    @UploadedFiles() banner, // use UploadedFiles instead of UploadedFile
    @Res() res: ExpressResponse,
  ) {
    try {
      const image = banner['banner'];

      if (image && image.size > limits.fileSize['image']) {
        return res.send(errorResponse(413, lan('common.limit_has_exceeded')));
      }

      if (image) {
        const attachmentUrl = `uploads/offer-banners/${image[0].filename}`;
        createOfferDto.banner = attachmentUrl;
      }

      await this.offersService.create(createOfferDto);
      res.send(successResponse(201, lan('common.request_submitted')));
    } catch (error) {
      res
        .status(HttpStatus.INTERNAL_SERVER_ERROR)
        .send(errorResponse(500, lan('common.internal_server_error'), error));

      saveError(error, this.apiLogRepository);
    }
  }

  @Get()
  @UseGuards(AuthMiddleware)
  async findAll(
    @Query('take') take: number,
    @Query('skip') skip: number,
    @Query('search') search: string,
    @Res() res: ExpressResponse,
    @Headers() headers: any,
  ) {
    try {
      const offers = await this.offersService.findAllOffers(
        take,
        skip,
        search,
        headers,
      );

      if (offers) {
        res
          .status(HttpStatus.OK)
          .send(
            successResponse(
              200,
              lan('common.data_retrieved_successfully'),
              offers,
            ),
          );
      }
    } catch (error) {
      res
        .status(HttpStatus.INTERNAL_SERVER_ERROR)
        .send(errorResponse(500, lan('common.internal_server_error'), error));

      saveError(error, this.apiLogRepository);
    }
  }

  @Get(':id')
  @UseGuards(AuthMiddleware)
  async findOne(@Param('id') id: string, @Res() res: ExpressResponse) {
    try {
      const offer = await this.offersService.findOffer(id);

      if (offer) {
        res
          .status(HttpStatus.OK)
          .send(
            successResponse(
              200,
              lan('common.data_retrieved_successfully'),
              offer,
            ),
          );
      }
    } catch (error) {
      if (
        error instanceof NotFoundException ||
        error instanceof BadRequestException
      ) {
        res
          .status(HttpStatus.BAD_REQUEST)
          .send(errorResponse(404, error.message));
      } else {
        res
          .status(HttpStatus.INTERNAL_SERVER_ERROR)
          .send(errorResponse(500, lan('common.internal_server_error'), error));
      }

      saveError(error, this.apiLogRepository);
    }
  }

  @Patch(':id')
  @UseInterceptors(FileInterceptor('banner', imageConfig))
  @UseGuards(AuthMiddleware)
  async update(
    @Param('id') id: string,
    @Body() updateOfferDto: UpdateOfferDto,
    @UploadedFile() banner,
    @Res() res: ExpressResponse,
  ) {
    try {
      if (banner && banner.size > limits.fileSize['image']) {
        return res.send(errorResponse(413, lan('common.limit_has_exceeded')));
      }

      if (banner) {
        const attachmentUrl = `uploads/offer-banners/${banner.filename}`;
        updateOfferDto.banner = attachmentUrl;
      }

      await this.offersService.updateOffer(id, updateOfferDto);

      res
        .status(HttpStatus.OK)
        .send(successResponse(200, lan('common.data_updated')));
    } catch (error) {
      if (
        error instanceof NotFoundException ||
        error instanceof BadRequestException
      ) {
        res
          .status(HttpStatus.BAD_REQUEST)
          .send(errorResponse(404, error.message));
      } else {
        res
          .status(HttpStatus.INTERNAL_SERVER_ERROR)
          .send(errorResponse(500, lan('common.internal_server_error'), error));
      }

      saveError(error, this.apiLogRepository);
    }
  }

  @Delete(':id')
  @UseGuards(AuthMiddleware)
  async remove(@Param('id') id: string, @Res() res: ExpressResponse) {
    try {
      await this.offersService.removeOffer(id);

      res
        .status(HttpStatus.OK)
        .send(successResponse(200, lan('common.data_deleted')));
    } catch (error) {
      if (
        error instanceof NotFoundException ||
        error instanceof BadRequestException
      ) {
        res
          .status(HttpStatus.BAD_REQUEST)
          .send(errorResponse(404, error.message));
      } else {
        res
          .status(HttpStatus.INTERNAL_SERVER_ERROR)
          .send(errorResponse(500, lan('common.internal_server_error'), error));
      }

      saveError(error, this.apiLogRepository);
    }
  }
}
