/**
 * Default Sales Return Side Effects Port Implementation
 */

import { pgGetSettings, pgSaveInventoryMovements } from '@/lib/postgres/data-access';
import type { SalesReturnSideEffectsPort } from '../application/sales-return-side-effects.port';
import type { SalesReturn } from '../domain/sales-return.model';

export class DefaultSalesReturnSideEffectsPort
  implements SalesReturnSideEffectsPort
{
  async recordInventoryReceipt(salesReturn: SalesReturn, byUserId?: string): Promise<void> {
    try {
      const legacyData = null;
      const settings = await pgGetSettings();
      const warehousesEnabled = settings.warehousesEnabled === true || settings.warehousesEnabled === 'true';
      const defaultWarehouseId = String(settings.defaultSalesWarehouseId || '').trim();
      const defaultShelfId = String(settings.defaultSalesShelfId || '').trim();

      const restockableItems = (salesReturn.items || []).filter(
        (item) => item.restockable && Number(item.returnedQuantity || 0) > 0
      );
      if (restockableItems.length === 0) {
        return;
      }

      const movements = restockableItems.map((item, index) => {
        const targetWarehouseId = String(
          item.restockWarehouseId || item.warehouseId || defaultWarehouseId
        ).trim();
        const targetShelfId = String(
          item.restockShelfId || item.shelfId || defaultShelfId
        ).trim();

        if (warehousesEnabled && (!targetWarehouseId || !targetShelfId)) {
          throw new Error(
            `Missing warehouse/shelf for returned item ${item.materialId}. Configure defaults or provide item destination.`
          );
        }

        return {
          id: `sales-return-${salesReturn.id}-${index + 1}-${Date.now()}`,
          date: salesReturn.receivedDate || salesReturn.date,
          materialId: item.materialId,
          warehouseId: targetWarehouseId,
          shelfId: targetShelfId,
          quantityIn: Number(item.returnedQuantity || 0),
          quantityOut: 0,
          referenceType: 'sales_return',
          referenceId: salesReturn.id,
          invoiceId: salesReturn.invoiceId,
          costPerUnitOriginal: Number(item.unitPrice || 0),
          shipmentId: salesReturn.shipmentId,
          notes: byUserId ? `Sales return received by ${byUserId}` : undefined,
        };
      });

      
      await pgSaveInventoryMovements(movements);
      
    } catch (error) {
      console.error('Failed to record inventory receipt for sales return:', error);
      throw error;
    }
  }

  async notifyReturnApproved(salesReturn: SalesReturn): Promise<void> {
    // TODO: Send email notification to customer
    console.log(`Return ${salesReturn.returnNumber} approved`);
  }

  async notifyReturnRejected(
    salesReturn: SalesReturn,
    reason: string
  ): Promise<void> {
    // TODO: Send email notification to customer
    console.log(
      `Return ${salesReturn.returnNumber} rejected: ${reason}`
    );
  }

  async notifyReturnReceived(salesReturn: SalesReturn): Promise<void> {
    // TODO: Send email notification to customer
    console.log(`Return ${salesReturn.returnNumber} received`);
  }

  async notifyRefundIssued(
    salesReturn: SalesReturn,
    amount: number,
    method: string
  ): Promise<void> {
    // TODO: Send email notification to customer
    console.log(
      `Refund of ${amount} issued for return ${salesReturn.returnNumber} via ${method}`
    );
  }

  async logActivity(params: {
    returnId: string;
    action: string;
    message: string;
    by: string;
    byName?: string;
  }): Promise<void> {
    // TODO: Log to activity log in database
    console.log(`[${params.action}] ${params.message}`);
  }
}
