/**
 * Default Sales Return Reference Data Port Implementation
 */

import { pgGetCustomers, pgGetMaterials } from '@/lib/postgres/data-access';
import { getSalesInvoiceService } from './sales-module-factory';
import type { SalesReturnReferenceDataPort } from '../application/sales-return-reference-data.port';

export class DefaultSalesReturnReferenceDataPort
  implements SalesReturnReferenceDataPort
{
  async getCustomer(customerId: string): Promise<{
    id: string;
    name: string;
    email?: string;
    phone?: string;
  } | null> {
    try {
      const normalizedId = String(customerId || '').trim();
      if (!normalizedId) return null;

      
      const result = await pgGetCustomers({ page: 1, pageSize: 5000 });
      const customer = (result.items || []).find(
      (entry: any) => String(entry.id || '').trim() === normalizedId
      );
      if (!customer) return null;
      return {
      id: String(customer.id || ''),
      name: String(customer.name || ''),
      phone: customer.phone ? String(customer.phone) : undefined,
        email: (customer as any).email ? String((customer as any).email) : undefined,
      };
    } catch (error) {
      console.error('Failed to get customer for sales return:', error);
      return null;
    }
  }

  async getMaterial(materialId: string): Promise<{
    id: string;
    name: string;
    price: number;
    unit: string;
  } | null> {
    try {
      const normalizedId = String(materialId || '').trim();
      if (!normalizedId) return null;

      
      const result = await pgGetMaterials({ page: 1, pageSize: 5000 });
      const material = (result.items || []).find(
      (entry: any) => String(entry.id || '').trim() === normalizedId
      );
      if (!material) return null;
      const mat: any = material;
      return {
      id: String(mat.id || ''),
      name: String(mat.name || mat.itemName || ''),
      price: Number(mat.salePrice || mat.price || 0),
      unit: String(mat.unit || mat.primaryUnit || ''),
      };
    } catch (error) {
      console.error('Failed to get material for sales return:', error);
      return null;
    }
  }

  async getInvoice(invoiceId: string): Promise<{
    id: string;
    invoiceNumber: string;
    date: string;
    customerId: string;
    items: Array<{
      materialId: string;
      name: string;
      quantity: number;
      unitPrice: number;
      warehouseId?: string;
      shelfId?: string;
    }>;
    totals: {
      subTotal: number;
      taxAmount: number;
      grandTotal: number;
    };
  } | null> {
    try {
      const normalizedId = String(invoiceId || '').trim();
      if (!normalizedId) return null;

      const invoice = await getSalesInvoiceService().getById(normalizedId);
      if (!invoice) return null;

      return {
        id: invoice.id,
        invoiceNumber: invoice.invoiceNumber,
        date: invoice.date,
        customerId: invoice.customerId,
        items: (invoice.items || []).map((item) => ({
          materialId: item.materialId,
          name: item.name,
          quantity: item.quantity,
          unitPrice: item.unitPrice,
          warehouseId: item.warehouseId,
          shelfId: item.shelfId,
        })),
        totals: {
          subTotal: Number(invoice.subTotal || 0),
          taxAmount: Number(invoice.taxAmount || 0),
          grandTotal: Number(invoice.grandTotal || 0),
        },
      };
    } catch (error) {
      console.error('Failed to get invoice for sales return:', error);
      return null;
    }
  }
}
