<?php

declare(strict_types=1);

namespace CloudXM\SDK\Providers;

use CloudXM\SDK\Contracts\ContainerInterface;

class MigrationServiceProvider
{
    public function __construct(
        private ContainerInterface $container
    ) {}

    public function register(): void
    {
        $this->container->singleton(\CloudXM\SDK\Persistence\MigrationRunner::class, function($c) {
            return new \CloudXM\SDK\Persistence\MigrationRunner(
                $c->get(\CloudXM\SDK\Contracts\ConfigurationInterface::class)
            );
        });

        add_action('plugins_loaded', [$this, 'runMigrationsOnLoad']);
    }

    public function runMigrationsOnLoad(): void
    {
        try {
            $migrationRunner = $this->container->get(\CloudXM\SDK\Persistence\MigrationRunner::class);
            $migrationRunner->runMigrations();
        } catch (\Exception $e) {
            \CloudXM\SDK\Logger::error('migrations_exception_on_load', [
                'error' => $e->getMessage(),
                'timestamp' => date('Y-m-d H:i:s')
            ]);
        }
    }
}