import httpStatus from 'http-status';
import { Request, Response } from 'express';

import catchAsync from '@/shared/utils/catchAsync';
import ApiError from '@/shared/utils/errors/ApiError';
import { getObjectId } from '@/shared/utils/commonHelper';
import responseCodes from '@/shared/utils/responseCode/responseCode.js';

import * as configurationService from './configuration.service';
import { pick } from '@/shared/utils';

const { ConfigurationResponseCodes } = responseCodes;

export const create = catchAsync(async (req: Request, res: Response) => {
  const configuration = await configurationService.create(req.body);
  res.success(
    configuration,
    ConfigurationResponseCodes.SUCCESS,
    'Configuration Fetched Successfully',
  );
});

export const list = catchAsync(async (req: Request, res: Response) => {
  const filters = pick(req.query, ['categoryId', 'subCategoryId', 'search']);

  const options = pick(req.query, [
    'sortBy',
    'limit',
    'page',
    'populate',
    'fields',
  ]);

  const result = await configurationService.queryConfiguration(
    filters,
    options,
  );

  res.success(
    result,
    ConfigurationResponseCodes.SUCCESS,
    'Configuration Fetched Successfully',
  );
});

export const get = catchAsync(async (req: Request, res: Response) => {
  const { id } = req.params;
  if (!getObjectId(id))
    throw new ApiError(httpStatus.BAD_REQUEST, 'Invalid ID');

  const configuration = await configurationService.getById(id);
  res.success(
    configuration,
    ConfigurationResponseCodes.SUCCESS,
    'Configuration Fetched Successfully',
  );
});

export const update = catchAsync(async (req: Request, res: Response) => {
  const { id } = req.params;
  if (!getObjectId(id))
    throw new ApiError(httpStatus.BAD_REQUEST, 'Invalid ID');

  await configurationService.update(id, req.body);
  res.success(
    true,
    ConfigurationResponseCodes.SUCCESS,
    'Configuration Fetched Successfully',
  );
});

export const remove = catchAsync(async (req: Request, res: Response) => {
  const { id } = req.params;
  if (!getObjectId(id))
    throw new ApiError(httpStatus.BAD_REQUEST, 'Invalid ID');

  await configurationService.remove(id);
  res.success(
    true,
    ConfigurationResponseCodes.SUCCESS,
    'Configuration Fetched Successfully',
  );
});
