<?php

namespace Modules\Inventory\Services;

use Illuminate\Support\Facades\DB;
use Modules\Inventory\Enums\AssetStatusEnum;
use Modules\Inventory\Enums\CategoryTypeEnum;
use Modules\Inventory\Models\Asset;
use Modules\Inventory\Models\AssetMovement;
use Modules\Inventory\Models\PurchaseInvoice;
use Modules\Inventory\Models\PurchaseInvoiceItem;
use Modules\Inventory\Models\Traits\GeneratesAssetCode;
use Modules\Inventory\Repositories\AssetMovementRepository;
use Modules\Inventory\Repositories\AssetRepository;

class PurchaseAssetService
{
    use GeneratesAssetCode;

    public function __construct(
        private AssetRepository $assetRepo,
        private AssetMovementRepository $movementRepo,
    ) {}

    public function createFromPurchase(PurchaseInvoice $invoice): void
    {
        foreach ($invoice->items as $item) {
            $product = $item->product;

            if ($product->category->category_type !== CategoryTypeEnum::ASSET->value) {
                continue;
            }

            $this->createAssets(
                invoice: $invoice,
                item: $item
            );
        }
    }

    private function createAssets(PurchaseInvoice $invoice, PurchaseInvoiceItem $item): void {

        $qty = (int) $item->base_qty;
        $costPerAsset = round(
            $item->net_amount / $qty,
            2
        );

        for ($i = 1; $i <= $qty; $i++) {
            $asset = $this->assetRepo->create([
                'product_id' => $item->product_id,
                'purchase_invoice_id' => $item->purchase_invoice_id,
                'purchase_invoice_item_id' => $item->id,
                'asset_code' => $this->generateAssetCode(),
                'inventory_department_id' => $item->product->inventory_department_id,
                'purchase_date' => $invoice->invoice_date,
                'purchase_cost' => $costPerAsset,
                'book_value' => $costPerAsset,
                'accumulated_depreciation' => 0,
                'status' => AssetStatusEnum::ACTIVE->value,
            ]);

            $this->movementRepo->create([
                'fiscal_year_id' => $invoice->fiscal_year_id,
                'accounting_period_id' => $invoice->accounting_period_id,
                'asset_id' => $asset->id,
                'from_department_id' => null,
                'to_department_id' => $asset->inventory_department_id,
                'date' => $invoice->invoice_date,
                'note' => 'Initial asset allocation',
            ]);
        }
    }
}
