<?php
namespace WorkbloomERP\Services;

use Throwable;
use KrothiumAPI\Database\DBManager;

class DBService {
    protected string $connection;
    protected ?string $schema;

    public function __construct(string $connection = 'DEFAULT', ?string $schema = 'shared') {
        $this->schema = $schema;
        $this->connection = strtoupper(string: $connection);
    }

    /**
     * Executa dentro de transação
     */
    public function transaction(callable $callback): mixed {
        DBManager::beginTransaction(connectionName: $this->connection, schema: $this->schema);
        try {
            $result = $callback($this);
            DBManager::commit(connectionName: $this->connection, schema: $this->schema);
            return $result;
        } catch (Throwable $e) {
            DBManager::rollback(connectionName: $this->connection, schema: $this->schema);
            throw $e;
        }
    }

    /**
     * Executa query sem retorno
     */
    public function execute(string $sql, array $params = []): bool {
        return DBManager::execute(
            sql: $sql,
            params: $params,
            connectionName: $this->connection,
            schema: $this->schema
        );
    }

    /**
     * Retorna um único registro
     */
    public function fetchOne(string $sql, array $params = []): ?array {
        return DBManager::fetchOne(
            sql: $sql,
            params: $params,
            connectionName: $this->connection,
            schema: $this->schema
        );
    }

    /**
     * Retorna múltiplos registros
     */
    public function fetchAll(string $sql, array $params = []): array {
        return DBManager::fetchAll(
            sql: $sql,
            params: $params,
            connectionName: $this->connection,
            schema: $this->schema
        );
    }

    /**
     * Último ID inserido (via PDO interno do driver)
     */
    public function lastInsertId(): string {
        return DBManager::lastInsertId(
            connectionName: $this->connection,
            schema: $this->schema
        );
    }
}