import { IResource, EntityType, IEventBus } from '../../types/CalendarTypes';
import { ResourceStore } from './ResourceStore';
import { BaseEntityService } from '../BaseEntityService';
import { IndexedDBContext } from '../IndexedDBContext';

/**
 * ResourceService - CRUD operations for resources in IndexedDB
 */
export class ResourceService extends BaseEntityService<IResource> {
  readonly storeName = ResourceStore.STORE_NAME;
  readonly entityType: EntityType = 'Resource';

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

  /**
   * Get all active resources
   */
  async getActive(): Promise<IResource[]> {
    const all = await this.getAll();
    return all.filter(r => r.isActive !== false);
  }

  /**
   * Get resources by IDs
   */
  async getByIds(ids: string[]): Promise<IResource[]> {
    if (ids.length === 0) return [];

    const results = await Promise.all(ids.map(id => this.get(id)));
    return results.filter((r): r is IResource => r !== null);
  }

  /**
   * Get resources by type
   */
  async getByType(type: string): Promise<IResource[]> {
    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction([this.storeName], 'readonly');
      const store = transaction.objectStore(this.storeName);
      const index = store.index('type');
      const request = index.getAll(type);

      request.onsuccess = () => {
        const data = request.result as IResource[];
        resolve(data);
      };

      request.onerror = () => {
        reject(new Error(`Failed to get resources by type ${type}: ${request.error}`));
      };
    });
  }
}
