<?php

declare(strict_types=1);

namespace App\Repositories;

use PDO;

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

    public function listWithBaseNames(): array
    {
        return $this->pdo->query("SELECT u.id, u.name, u.symbol, u.base_unit_id, u.factor_to_base, b.name base_name FROM units u LEFT JOIN units b ON b.id=u.base_unit_id ORDER BY u.name")->fetchAll() ?: [];
    }

    public function all(): array
    {
        return $this->pdo->query("SELECT id, name, base_unit_id FROM units ORDER BY name")->fetchAll() ?: [];
    }

    public function baseUnits(): array
    {
        return $this->pdo->query("SELECT id, name FROM units WHERE base_unit_id IS NULL ORDER BY name")->fetchAll() ?: [];
    }

    public function findById(int $id): array|false
    {
        $st = $this->pdo->prepare("SELECT id, name, symbol, base_unit_id, factor_to_base FROM units WHERE id=? LIMIT 1");
        $st->execute([$id]);
        return $st->fetch();
    }

    public function countItemsUsingAsDefault(int $id): int
    {
        $st = $this->pdo->prepare("SELECT COUNT(*) FROM items WHERE default_unit_id=?");
        $st->execute([$id]);
        return (int)($st->fetchColumn() ?: 0);
    }

    public function create(array $data): int
    {
        $this->pdo->prepare("INSERT INTO units (name, symbol, base_unit_id, factor_to_base) VALUES (?,?,?,?)")
            ->execute([$data['name'], $data['symbol'], $data['base_unit_id'], $data['factor_to_base']]);
        return (int)$this->pdo->lastInsertId();
    }

    public function update(int $id, array $data): void
    {
        $this->pdo->prepare("UPDATE units SET name=?, symbol=?, base_unit_id=?, factor_to_base=? WHERE id=?")
            ->execute([$data['name'], $data['symbol'], $data['base_unit_id'], $data['factor_to_base'], $id]);
    }

    public function delete(int $id): void
    {
        $this->pdo->prepare("DELETE FROM units WHERE id=?")->execute([$id]);
    }
}
