import httpStatus from 'http-status';
import Category from './category.model';
import { ICategory } from '../property.interfaces';
import ApiError from '@/shared/utils/errors/ApiError';
import responseCodes from '@/shared/utils/responseCode/responseCode';
import { defaultStatus } from '@/shared/utils/responseCode/httpStatusAlias';
import { safeDeleteById } from '@/shared/utils/guard/ref-guard';

const { CategoryResponseCodes } = responseCodes;

export const create = async (body: ICategory): Promise<ICategory> => {
  const { name } = body;

  const existing = await Category.findOne({
    name: name?.toLowerCase().trim(),
  });

  if (existing)
    throw new ApiError(
      defaultStatus.BAD_REQUEST,
      'Category with this name already exists.',
      true,
      '',
      CategoryResponseCodes.CATEGORY_ALREADY_EXISTS,
    );

  return await Category.create(body);
};

export const getById = async (id: string): Promise<ICategory> => {
  const category = await Category.findById(id);
  if (!category) throw new ApiError(httpStatus.NOT_FOUND, 'Category not found');
  return category;
};

export const update = async (
  id: string,
  body: Partial<ICategory>,
): Promise<ICategory> => {
  const category = await Category.findByIdAndUpdate(id, body, {
    new: true,
    runValidators: true,
  });
  if (!category) throw new ApiError(httpStatus.NOT_FOUND, 'Category not found');
  return category;
};

export const remove = async (id: string): Promise<boolean> => {
 await safeDeleteById(Category, id, CategoryResponseCodes.CATEGORY_IN_USE);
  return true;
};

export const list = (query: Record<string, unknown>): Promise<ICategory[]> => Category.find(query);

// Add pagination support
export const paginate = (
  filters: Record<string, unknown>,
  options: {
    page: number;
    limit: number;
    sortBy: string;
  },
) => Category.paginate(filters, options);
