/**
 * Default Sales Reference Data Port Adapter
 * Fetches reference data from existing data functions
 * Bridges the module with existing application data
 */

import { pgGetCustomers, pgGetSuppliers } from '@/lib/postgres/data-access';

import {
  SalesReferenceDataPort,
  Customer,
  Material,
  Warehouse,
  Currency,
  SalesRep,
} from '../application/sales-reference-data.port';

export class DefaultSalesReferenceDataPort implements SalesReferenceDataPort {
  /**
   * Get customer details — supports both customer IDs and supplier IDs (prefixed with "sup_")
   */
  async getCustomer(id: string): Promise<Customer | null> {
    try {
      const normalizedId = String(id || '').trim();

      if (normalizedId.startsWith('sup_')) {
        const supplierId = normalizedId.slice(4);
        let suppliers: any[];
        
        suppliers = (await pgGetSuppliers({ page: 1, pageSize: 5000 })).items || [];
        
        const supplier = suppliers.find((s: any) => String(s.id || '') === supplierId);
        if (!supplier) return null;
        return { id: normalizedId, name: String(supplier.name || ''), phone: String(supplier.phone || '') };
      }

      let customers: any[];
      
      customers = (await pgGetCustomers({ page: 1, pageSize: 5000 })).items || [];
      
      const customer = customers.find((c: any) => String(c.id || '') === normalizedId);
      if (!customer) return null;
      return {
        id: String(customer.id || ''),
        name: String(customer.name || ''),
        category: customer.category ? String(customer.category) : undefined,
        phone: customer.phone ? String(customer.phone) : undefined,
        creditLimit: typeof customer.creditLimit === 'number' ? customer.creditLimit : undefined,
        allowedDiscount: typeof customer.allowedDiscount === 'number' ? customer.allowedDiscount : undefined,
      };
    } catch (error) {
      console.error('Failed to get customer:', error);
      return null;
    }
  }

  /**
   * List all customers
   */
  async listCustomers(options?: {
    category?: string;
    search?: string;
  }): Promise<Customer[]> {
    try {
      // TODO: Call actual data function
      // const customers = await getCustomers(options);
      return [];
    } catch (error) {
      console.error('Failed to list customers:', error);
      return [];
    }
  }

  /**
   * Get material details
   */
  async getMaterial(id: string): Promise<Material | null> {
    try {
      // TODO: Call actual data function
      return null;
    } catch (error) {
      console.error('Failed to get material:', error);
      return null;
    }
  }

  /**
   * List all materials for sale
   */
  async listMaterials(options?: {
    category?: string;
    search?: string;
  }): Promise<Material[]> {
    try {
      // TODO: Call actual data function
      return [];
    } catch (error) {
      console.error('Failed to list materials:', error);
      return [];
    }
  }

  /**
   * Get warehouse details
   */
  async getWarehouse(id: string): Promise<Warehouse | null> {
    try {
      // TODO: Call actual data function
      return null;
    } catch (error) {
      console.error('Failed to get warehouse:', error);
      return null;
    }
  }

  /**
   * List all warehouses
   */
  async listWarehouses(): Promise<Warehouse[]> {
    try {
      // TODO: Call actual data function
      return [];
    } catch (error) {
      console.error('Failed to list warehouses:', error);
      return [];
    }
  }

  /**
   * Get currency details
   */
  async getCurrency(code: string): Promise<Currency | null> {
    try {
      // TODO: Call actual data function
      return null;
    } catch (error) {
      console.error('Failed to get currency:', error);
      return null;
    }
  }

  /**
   * List all currencies
   */
  async listCurrencies(): Promise<Currency[]> {
    try {
      // TODO: Call actual data function
      return [];
    } catch (error) {
      console.error('Failed to list currencies:', error);
      return [];
    }
  }

  /**
   * Get base currency code
   */
  async getBaseCurrencyCode(): Promise<string> {
    try {
      // TODO: Call actual data function
      return 'USD';
    } catch (error) {
      console.error('Failed to get base currency:', error);
      return 'USD';
    }
  }

  /**
   * Get sales rep details
   */
  async getSalesRep(id: string): Promise<SalesRep | null> {
    try {
      // TODO: Call actual data function
      return null;
    } catch (error) {
      console.error('Failed to get sales rep:', error);
      return null;
    }
  }

  /**
   * List all sales reps
   */
  async listSalesReps(): Promise<SalesRep[]> {
    try {
      // TODO: Call actual data function
      return [];
    } catch (error) {
      console.error('Failed to list sales reps:', error);
      return [];
    }
  }

  /**
   * Get customer pricing for material
   */
  async getCustomerPricing(
    customerId: string,
    materialId: string
  ): Promise<number | null> {
    try {
      // TODO: Call actual data function
      return null;
    } catch (error) {
      console.error('Failed to get customer pricing:', error);
      return null;
    }
  }

  /**
   * Get customer category pricing adjustments
   */
  async getCategoryPricing(category: string): Promise<Record<string, number> | null> {
    try {
      // TODO: Call actual data function
      return null;
    } catch (error) {
      console.error('Failed to get category pricing:', error);
      return null;
    }
  }
}
