import { EntityType, IEventBus } from '../../types/CalendarTypes';
import {
  TenantSetting,
  IWorkweekSettings,
  IGridSettings,
  ITimeFormatSettings,
  IViewSettings,
  IWorkweekPreset,
  SettingsIds
} from '../../types/SettingsTypes';
import { SettingsStore } from './SettingsStore';
import { BaseEntityService } from '../BaseEntityService';
import { IndexedDBContext } from '../IndexedDBContext';

/**
 * SettingsService - CRUD operations for tenant settings
 *
 * Settings are stored as separate records per section.
 * This service provides typed methods for accessing specific settings.
 */
export class SettingsService extends BaseEntityService<TenantSetting> {
  readonly storeName = SettingsStore.STORE_NAME;
  readonly entityType: EntityType = 'Settings';

  constructor(context: IndexedDBContext, eventBus: IEventBus) {
    super(context, eventBus);
  }

  /**
   * Get workweek settings
   */
  async getWorkweekSettings(): Promise<IWorkweekSettings | null> {
    return this.get(SettingsIds.WORKWEEK) as Promise<IWorkweekSettings | null>;
  }

  /**
   * Get grid settings
   */
  async getGridSettings(): Promise<IGridSettings | null> {
    return this.get(SettingsIds.GRID) as Promise<IGridSettings | null>;
  }

  /**
   * Get time format settings
   */
  async getTimeFormatSettings(): Promise<ITimeFormatSettings | null> {
    return this.get(SettingsIds.TIME_FORMAT) as Promise<ITimeFormatSettings | null>;
  }

  /**
   * Get view settings
   */
  async getViewSettings(): Promise<IViewSettings | null> {
    return this.get(SettingsIds.VIEWS) as Promise<IViewSettings | null>;
  }

  /**
   * Get workweek preset by ID
   */
  async getWorkweekPreset(presetId: string): Promise<IWorkweekPreset | null> {
    const settings = await this.getWorkweekSettings();
    if (!settings) return null;
    return settings.presets[presetId] || null;
  }

  /**
   * Get the default workweek preset
   */
  async getDefaultWorkweekPreset(): Promise<IWorkweekPreset | null> {
    const settings = await this.getWorkweekSettings();
    if (!settings) return null;
    return settings.presets[settings.defaultPreset] || null;
  }

  /**
   * Get all available workweek presets
   */
  async getWorkweekPresets(): Promise<IWorkweekPreset[]> {
    const settings = await this.getWorkweekSettings();
    if (!settings) return [];
    return Object.values(settings.presets);
  }
}
