<?php

namespace Modules\Inventory\Services\ApprovalHandlers;

use Illuminate\Database\Eloquent\Model;
use Modules\Approval\Contracts\ApprovalHandlerInterface;
use Modules\Approval\Models\ApprovalRequest;
use Modules\Inventory\Enums\PurchaseRequisitionStatusEnum;
use Modules\Inventory\Models\PurchaseInvoice;
use Modules\Inventory\Services\PurchaseInvoicePostingService;

class PurchaseInvoiceApprovalHandler implements ApprovalHandlerInterface
{
    public function __construct(
        protected PurchaseInvoicePostingService $postingService,
    ) {}

    public function approved0(Model $document, ApprovalRequest $request): void
    {

        /** @var PurchaseInvoice $document */

        $this->postingService->post($document);
    }

    public function approved(Model $document, ApprovalRequest $request): void
    {
        $document->update([
            'status' => PurchaseRequisitionStatusEnum::APPROVED->value,
            'approved_at' => now(),
        ]);
    }

    public function rejected(Model $document, ApprovalRequest $request, ?string $remarks = null): void
    {
        $document->update([
            'status' => PurchaseRequisitionStatusEnum::REJECTED->value,
            'rejected_at' => now(),
            // 'remarks' => $remarks
        ]);
    }

    // If Final Approval, then Inventory Posting, Accounting Posting
    /* public function handle(PurchaseInvoice $invoice): void {

        DB::transaction(function () use ($invoice) {

            $this->inventoryPostingService
                ->post($invoice);

            $this->purchaseAccountingPostingService
                ->post($invoice);

            $invoice->update([
                'status' => PurchaseStatusEnum::APPROVED->value,
                'approved_at' => now(),
                'approved_by' => auth()->id(),
                'is_posted' => true,
            ]);

            $invoice->purchaseRequisition->update([
                'status' => PurchaseRequisitionStatusEnum::CLOSED->value,
                'closed_at' => now(),
            ]);

        });

    } */
}
