import { ICustomer, EntityType, IEventBus } from '../../types/CalendarTypes';
import { CustomerStore } from './CustomerStore';
import { BaseEntityService } from '../BaseEntityService';
import { IndexedDBContext } from '../IndexedDBContext';

/**
 * CustomerService - CRUD operations for customers in IndexedDB
 */
export class CustomerService extends BaseEntityService<ICustomer> {
  readonly storeName = CustomerStore.STORE_NAME;
  readonly entityType: EntityType = 'Customer';

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

  /**
   * Search customers by name (case-insensitive contains)
   */
  async searchByName(query: string): Promise<ICustomer[]> {
    const all = await this.getAll();
    const lowerQuery = query.toLowerCase();
    return all.filter(c => c.name.toLowerCase().includes(lowerQuery));
  }

  /**
   * Find customer by phone
   */
  async getByPhone(phone: string): Promise<ICustomer | null> {
    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction([this.storeName], 'readonly');
      const store = transaction.objectStore(this.storeName);
      const index = store.index('phone');
      const request = index.get(phone);

      request.onsuccess = () => {
        const data = request.result;
        resolve(data ? (data as ICustomer) : null);
      };

      request.onerror = () => {
        reject(new Error(`Failed to find customer by phone ${phone}: ${request.error}`));
      };
    });
  }
}
