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 categoryService from './category.service';

const { CategoryResponseCodes } = responseCodes;

export const create = catchAsync(async (req: Request, res: Response) => {
  const category = await categoryService.create(req.body);
  res.success(category, CategoryResponseCodes.SUCCESS, 'Category Fetched Successfully');
});

export const list = catchAsync(async (req: Request, res: Response) => {
  const { page = 1, limit = 10, sortBy, search, ...filters } = req.query;

  if (search && typeof search === 'string') 
    filters.name = { $regex: search, $options: 'i' };
  
  const options = {
    page: Number(page),
    limit: Number(limit),
    sortBy: String(sortBy),
  };

  const result = await categoryService.paginate(filters, options);
  res.success(result, CategoryResponseCodes.SUCCESS, 'Category 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 category = await categoryService.getById(id);
  res.success(category, CategoryResponseCodes.SUCCESS, 'Category 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 categoryService.update(id, req.body);
  res.success(true, CategoryResponseCodes.SUCCESS, 'Category 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 categoryService.remove(id);
  res.success(true, CategoryResponseCodes.SUCCESS, 'Category Fetched Successfully');
});
