<?php

namespace App\Modules\Finance\Listeners;

use App\Modules\Inventory\Events\GoodsReceiptApprovedEvent;
use App\Modules\Finance\Services\AccountPayableService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

class CreateAccountPayableFromGoodsReceipt
{
    protected AccountPayableService $accountPayableService;

    /**
     * Create the event listener.
     */
    public function __construct(AccountPayableService $accountPayableService)
    {
        $this->accountPayableService = $accountPayableService;
    }

    /**
     * Handle the event.
     */
    public function handle(GoodsReceiptApprovedEvent $event): void
    {
        try {
            // 目前使用系統預設 User ID 或 0 作為自動生成的建立者，若能從 event 取得更好
            $userId = auth()->id() ?? 1; // 假設 1 為系統管理員或預設使用者
            
            $this->accountPayableService->createFromGoodsReceipt($event->goodsReceiptId, $userId);
            
            Log::info("已成功為進貨單 ID: {$event->goodsReceiptId} 建立應付帳款");
        } catch (\Exception $e) {
            Log::error("建立應付帳款失敗 (進貨單 ID: {$event->goodsReceiptId}): " . $e->getMessage());
            // 根據需求決定是否拋出 exception 或只記錄 log
            throw $e;
        }
    }
}
