<?php

namespace Modules\Bms\Services\Adapters\Erp;

use Illuminate\Support\Facades\DB;
use Modules\Bms\Services\Contracts\PurchaseServiceContract;

/**
 * Purchasing adapter. Event-stock shortfalls raise a Purchase Requisition via
 * the PurchaseRequisition module (PrRequest + PrProduct lines). The module is
 * an optional dependency — when it is not installed, the call no-ops (returns
 * null) so BMS stays portable.
 */
class ErpPurchaseService implements PurchaseServiceContract
{
    public function createPurchaseRequest(int $businessId, array $lines, array $meta = []): ?int
    {
        $lines = array_values(array_filter($lines, fn ($l) => (float) ($l['quantity'] ?? 0) > 0 && ! empty($l['product_id'])));
        if (empty($lines)) {
            return null;
        }

        $prRequest = '\Modules\PurchaseRequisition\Entities\PrRequest';
        $prProduct = '\Modules\PurchaseRequisition\Entities\PrProduct';
        if (! class_exists($prRequest) || ! class_exists($prProduct)) {
            \Log::info('[BMS] PurchaseRequisition module absent — shortfall PR skipped.');
            return null;
        }

        $userId = $meta['created_by'] ?? auth()->id() ?? \App\User::where('business_id', $businessId)->min('id');
        $locationId = $meta['location_id'] ?? ($lines[0]['location_id'] ?? null);

        return DB::transaction(function () use ($prRequest, $prProduct, $businessId, $lines, $userId, $locationId, $meta) {
            $req = $prRequest::create([
                'business_id'      => $businessId,
                'ref_no'           => $this->nextRefNo($businessId, $prRequest),
                'transaction_date' => now(),
                'location_id'      => $locationId,
                'status'           => 'draft',
                'notes'            => $meta['notes'] ?? 'Auto-raised from BMS event shortfall',
                'created_by'       => $userId,
            ]);

            foreach ($lines as $l) {
                $prProduct::create([
                    'business_id'       => $businessId,
                    'pr_request_id'     => $req->id,
                    'product_id'        => $l['product_id'],
                    'variation_id'      => $l['variation_id'] ?? null,
                    'current_stock'     => $l['current_stock'] ?? 0,
                    'required_quantity' => $l['quantity'],
                    'pending_purchase_qty' => $l['quantity'],
                    'notes'             => $l['notes'] ?? null,
                ]);
            }

            return (int) $req->id;
        });
    }

    /** Sequential ref no, prefixed to avoid colliding with manual PRs. */
    protected function nextRefNo(int $businessId, string $prRequest): string
    {
        $seq = (int) $prRequest::where('business_id', $businessId)->count() + 1;
        return 'PR-BMS-' . str_pad((string) $seq, 5, '0', STR_PAD_LEFT);
    }
}
