<?php

declare(strict_types=1);

namespace App\Modules\Inventory\Application\Services;

use PDO;

final class ItemBalanceService
{
    public function __construct(private PDO $pdo)
    {
    }

    /** @return array<string,mixed> */
    public function data(int $warehouseId, int $itemId): array
    {
        $warehouses = get_warehouses($this->pdo);
        $items = $this->pdo->query('SELECT id, name, barcode, is_active FROM items WHERE is_active=1 ORDER BY name LIMIT 2000')->fetchAll() ?: [];

        if ($warehouseId <= 0) {
            $warehouseId = main_warehouse_id($this->pdo);
        }

        $balance = null;
        $moves = [];

        if ($itemId > 0) {
            $st = $this->pdo->prepare("SELECT i.id, i.name, i.barcode, i.cost,
                                COALESCE(sb.qty,0) qty
                         FROM items i
                         LEFT JOIN stock_balances sb ON sb.item_id=i.id AND sb.warehouse_id=?
                         WHERE i.id=?");
            $st->execute([$warehouseId, $itemId]);
            $balance = $st->fetch() ?: null;

            $mv = $this->pdo->prepare("SELECT created_at, ref_type, ref_id, qty_in, qty_out, cost
                         FROM stock_moves
                         WHERE warehouse_id=? AND item_id=?
                         ORDER BY id DESC
                         LIMIT 20");
            $mv->execute([$warehouseId, $itemId]);
            $moves = $mv->fetchAll() ?: [];
        }

        return [
            'warehouses' => $warehouses,
            'items' => $items,
            'warehouse_id' => $warehouseId,
            'item_id' => $itemId,
            'balance' => $balance,
            'moves' => $moves,
        ];
    }
}
