import { WidgetTypeModel } from '../models';
import { jsonStore } from '../data/json-store';
import { WidgetType } from '../types';
import { config } from '../config/env';
import { formatWidgetType } from '../utils/response-formatter';

export class WidgetTypesService {
  async getWidgetTypes(
    sportId?: number,
    leagueId?: number,
    isActive?: boolean
  ): Promise<WidgetType[]> {
    if (config.useJsonStore) {
      return jsonStore.getWidgetTypes(sportId, leagueId, isActive).map(formatWidgetType);
    }

    const filter: Record<string, unknown> = {};

    if (sportId !== undefined) {
      filter.sportId = sportId;
    }

    if (leagueId !== undefined) {
      filter.leagueId = leagueId;
    }

    if (isActive !== undefined) {
      filter.isActive = isActive;
    }

    const widgetTypes = await WidgetTypeModel.find(filter).sort({ widgetName: 1 });
    return widgetTypes.map(w => formatWidgetType(w.toJSON()));
  }
}

export const widgetTypesService = new WidgetTypesService();
