import { TemplateModel } from '../models';
import { jsonStore } from '../data/json-store';
import { Template, TemplateWithEmbed } from '../types';
import { config } from '../config/env';
import { formatTemplateWithEmbed } from '../utils/response-formatter';

export class TemplatesService {
  async getTemplates(filters: {
    sportId?: number;
    leagueId?: number;
    widgetTypeId?: number;
    participantId?: number;
    featured?: boolean;
    isActive?: boolean;
  }): Promise<TemplateWithEmbed[]> {
    if (config.useJsonStore) {
      const templates = jsonStore.getTemplates(filters);
      return templates.map(t => formatTemplateWithEmbed(this.addEmbedCodes(t)));
    }

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

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

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

    if (filters.widgetTypeId !== undefined) {
      filter.widgetTypeId = filters.widgetTypeId;
    }

    if (filters.participantId !== undefined) {
      filter.participantId = filters.participantId;
    }

    if (filters.featured !== undefined) {
      filter.featured = filters.featured;
    }

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

    const templates = await TemplateModel.find(filter).sort({ templateName: 1 });
    return templates.map(t => formatTemplateWithEmbed(this.addEmbedCodes(t.toJSON())));
  }

  private addEmbedCodes(template: Template): TemplateWithEmbed {
    return {
      ...template,
      embedCodeLight: template.lightThemeUrl ? this.generateEmbedCode(template.lightThemeUrl, 'light') : null,
      embedCodeDark: template.darkThemeUrl ? this.generateEmbedCode(template.darkThemeUrl, 'dark') : null,
    };
  }

  private generateEmbedCode(url: string, theme: 'light' | 'dark'): string {
    return `<iframe src="${url}" width="100%" height="600" frameborder="0" scrolling="no" title="SportPulse Widget - ${theme} theme"></iframe>`;
  }
}

export const templatesService = new TemplatesService();
