<?php

declare(strict_types=1);

namespace App\Services;

use App\Repositories\WarehouseRepository;
use InvalidArgumentException;
use PDO;
use RuntimeException;

final class WarehouseService
{
    public function __construct(private PDO $pdo, private WarehouseRepository $warehouses) {}

    public function save(array $input): void
    {
        $id = (int)($input['id'] ?? 0);
        $name = trim((string)($input['name'] ?? ''));
        if ($name === '') {
            throw new InvalidArgumentException('اسم المخزن مطلوب');
        }

        $data = [
            'code' => trim((string)($input['code'] ?? '')) ?: null,
            'name' => $name,
            'is_main' => !empty($input['is_main']) ? 1 : 0,
            'is_active' => !empty($input['is_active']) ? 1 : 0,
            'allow_negative' => $this->warehouses->hasAllowNegativeColumn() && !empty($input['allow_negative']) ? 1 : 0,
        ];

        try {
            $this->pdo->beginTransaction();
            if ($data['is_main'] === 1) {
                $this->warehouses->clearMainFlag();
            }
            if ($id > 0) {
                if (!$this->warehouses->findById($id)) {
                    throw new RuntimeException('المخزن غير موجود');
                }
                $this->warehouses->update($id, $data);
            } else {
                $this->warehouses->create($data);
            }
            $this->pdo->commit();
        } catch (\Throwable $e) {
            if ($this->pdo->inTransaction()) {
                $this->pdo->rollBack();
            }
            throw $e;
        }
    }
}
