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

@Controller('categories')
@UseGuards(AuthMiddleware)
export class CategoriesController {
  constructor(
    private readonly categoriesService: CategoriesService,
    @InjectRepository(ApiLog)
    private readonly apiLogRepository: Repository<ApiLog>,
  ) {}

  @Post()
  @UseInterceptors(
    FileFieldsInterceptor([{ name: 'media', maxCount: 1 }], imageConfig),
    FileValidationInterceptor,
  )
  @UsePipes(
    new ValidationPipe({
      exceptionFactory: validationErrorMessage,
      transform: true,
      transformOptions: {
        enableImplicitConversion: true,
      },
    }),
  )
  async create(
    @Body() createCategoryDto: CreateCategoryDto,
    @UploadedFiles() media,
    @Res() res: ExpressResponse,
  ) {
    try {
      const image = media['media'];

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

      if (image) {
        const attachmentUrl = `uploads/category/${image[0].filename}`;
        createCategoryDto.media = attachmentUrl;
      }
      await this.categoriesService.create(createCategoryDto);
      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,
    @Query('search') search: string,
    @Query('is_active') isActive: any,
    @Res() res: ExpressResponse,
    @Headers() headers: any,
  ) {
    try {
      const categories = await this.categoriesService.findAll(
        take,
        skip,
        search,
        headers,
        isActive,
      );
      res
        .status(HttpStatus.OK)
        .send(
          successResponse(
            200,
            lan('common.data_retrieved_successfully'),
            categories,
          ),
        );
    } catch (error) {
      res
        .status(HttpStatus.INTERNAL_SERVER_ERROR)
        .send(errorResponse(500, lan('common.internal_server_error'), error));

      saveError(error, this.apiLogRepository);
    }
  }

  @Get(':id')
  async findOne(@Param('id') id: string, @Res() res: ExpressResponse) {
    try {
      const data = await this.categoriesService.findOne(id);
      res
        .status(HttpStatus.OK)
        .send(
          successResponse(200, lan('common.data_retrieved_successfully'), data),
        );
    } catch (error) {
      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));
      }

      saveError(error, this.apiLogRepository);
    }
  }

  @Patch(':id')
  @UseInterceptors(FileInterceptor('media', imageConfig))
  @UsePipes(
    new ValidationPipe({
      exceptionFactory: validationErrorMessage,
      transform: true,
      transformOptions: {
        enableImplicitConversion: true,
      },
    }),
  )
  async update(
    @Param('id') id: string,
    @Body() updateCategoryDto: UpdateCategoryDto,
    @UploadedFile() media,
    @Res() res: ExpressResponse,
  ) {
    try {
      if (media && media.size > limits.fileSize['image']) {
        return res.send(errorResponse(413, lan('common.limit_has_exceeded')));
      }

      if (media) {
        const attachmentUrl = `uploads/category/${media.filename}`;
        updateCategoryDto.media = attachmentUrl;
      }
      const data = await this.categoriesService.update(id, updateCategoryDto);
      res
        .status(HttpStatus.OK)
        .send(successResponse(200, lan('common.data_updated'))),
        data;
    } 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')
  async remove(@Param('id') id: string, @Res() res: ExpressResponse) {
    try {
      await this.categoriesService.remove(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);
    }
  }
}
