import { ApiError } from '@/shared/utils/errors';
import { defaultStatus } from '@/shared/utils/responseCode/httpStatusAlias';
import { ClickStats } from '@/modules/clickStats/clickStats.model';
import {
  NewCreatedClickStats,
  ClickAction,
  ClickType,
} from '@/modules/clickStats/clickStats.interface';
import responseCodes from '@/shared/utils/responseCode/responseCode';
import { getObjectId } from '@/shared/utils/commonHelper';

const { ClickStatsResponseCodes } = responseCodes;

// Create new click stat
export const createClickStats = async (
  data: NewCreatedClickStats,
): Promise<boolean> => {
  const clickStat = await ClickStats.create(data);

  if (!clickStat) 
    throw new ApiError(
      defaultStatus.OK,
      'Failed to create ClickStats',
      true,
      '',
      ClickStatsResponseCodes.CLICKSTATS_ERROR,
    );
  

  return true;
};

// Get counts grouped by action for a given type + propertyId
export const getClickStatsCounts = async (filter: {
  type?: ClickType;
  propertyId?: string;
}) => {
  const { type, propertyId } = filter;

  if (!type || !propertyId) 
    throw new ApiError(
      defaultStatus.BAD_REQUEST,
      'Type and propertyId are required',
      false,
      '',
      ClickStatsResponseCodes.CLICKSTATS_ERROR,
    );
  

  const stats = await ClickStats.aggregate([
    {
      $match: {
        type,
        propertyId: getObjectId(propertyId),
      },
    },
    {
      $group: {
        _id: '$action',
        count: { $sum: 1 },
      },
    },
  ]);

  // Convert aggregation result into { shared: X, opened: Y }
  const result: Record<ClickAction, number> = {
    shared: 0,
    opened: 0,
  };

  stats.forEach((s) => {
    result[s._id as ClickAction] = s.count;
  });

  return result;
};
