<?php

namespace App\Controllers\CLI\DBMigration;

use App\Controllers\BaseController;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Libraries\DBMigration\Process\MigrationProcessInterface;

abstract class DBMigration extends BaseController
{
    private $_targetDB = null;

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
    }

    abstract protected function getSourceDB(): BaseConnection;
    abstract protected function getClient(): array;
    abstract protected function getLine(): array;
    abstract protected function getServerCode(): array;
    abstract protected function getSWITCHCode(): array;
    final protected function getTargetDB(): BaseConnection
    {
        if ($this->_targetDB === null) {
            $this->_targetDB = \Config\Database::connect('default');
        }
        return $this->_targetDB;
    }

    /**
     * 공통 마이그레이션 처리 로직
     */
    final protected function execute(MigrationProcessInterface $processor, array $rows, string $functionName, string $site): void
    {
        $this->getTargetDB()->transStart();
        $total = count($rows);
        $cnt = 1;
        try {
            foreach ($rows as $row) {
                $processor->process($site, $row, $cnt);
                echo "{$site} => {$cnt} 번째/{$total} => {$functionName} 작업을 완료하였습니다.";
                $cnt++;
            }
            $this->getTargetDB()->transCommit();
        } catch (\Exception $e) {
            $this->getTargetDB()->transRollback();
            echo "{$site} => {$cnt} 번째/{$total} {$functionName} 작업을 실패하였습니다.\n--------------\n" . $e->getMessage() . "\n--------------\n";
        }
    }
}
