<?php
/**
 * BookiFlex Core
 *
 * @package    BookiFlex
 * @subpackage Core
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */


declare(strict_types=1);
namespace BookiFlex\Core\ORM\Schema;

use Cycle\Database\DatabaseInterface;
use Throwable;

defined( 'ABSPATH' ) || exit;

class TimestampFixer
{
    public function __construct(
        protected DatabaseInterface $database
    ) {
    }

    /**
     * Add ON UPDATE CURRENT_TIMESTAMP for fields updated_at on set tables.
     */
    public function addOnUpdateCurrentTimestamp(array $tables, string $column = 'updated_at'): void
    {
        $driver = $this->database->getDriver();

        $driver->beginTransaction();

        try {
            foreach ($tables as $table) {
                $sql = sprintf(
                    'ALTER TABLE `%s` MODIFY `%s` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
                    $table,
                    $column
                );

                $driver->execute($sql);
            }

            $driver->commitTransaction();
        } catch (Throwable $e) {
            $driver->rollbackTransaction();
            throw $e;
        }
    }
}
