#!/usr/bin/env php
<?php
/*
 * Copyright 2026 Alessandro Chiapparini <sprint_planer_web@chiapparini.org>
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * See the LICENSE file in the project root for the full license text.
 */

declare(strict_types=1);

/**
 * R01-N22: deploy-time migration runner.
 *
 * Called by the Docker entrypoint before Apache starts, and by operators
 * directly when applying a new release outside Docker. The web request path
 * (`public/index.php`) only checks `Migrator::pendingFiles()` and refuses
 * to serve when there is anything pending — it does NOT apply SQL itself.
 *
 * Exits 0 on success (including the no-op "already current" case) and 1 on
 * any failure, with a one-line message on stderr. Stdout reports what was
 * applied so the entrypoint log shows it.
 */

use App\Db\Connection;
use App\Db\Migrator;

$root = dirname(__DIR__);
require $root . '/vendor/autoload.php';

if (is_file($root . '/.env')) {
    Dotenv\Dotenv::createImmutable($root)->safeLoad();
}

try {
    $pdo = Connection::pdo();
    $migrator = new Migrator($pdo);
    $applied = $migrator->migrate();
} catch (Throwable $e) {
    fwrite(STDERR, 'migrate: ' . $e->getMessage() . PHP_EOL);
    exit(1);
}

if ($applied === []) {
    fwrite(STDOUT, 'migrate: schema already current (version ' . $migrator->currentVersion() . ')' . PHP_EOL);
} else {
    fwrite(STDOUT, 'migrate: applied ' . count($applied) . ' migration(s):' . PHP_EOL);
    foreach ($applied as $f) {
        fwrite(STDOUT, '  - ' . $f . PHP_EOL);
    }
    fwrite(STDOUT, 'migrate: schema now at version ' . $migrator->currentVersion() . PHP_EOL);
}
exit(0);
