<?php

declare(strict_types=1);

namespace WhmcsMigrate\Phases;

use WhmcsMigrate\Config;
use WhmcsMigrate\Database;
use WhmcsMigrate\Encryptor;
use WhmcsMigrate\ExportManager;
use WhmcsMigrate\Logger;
use WhmcsMigrate\StateManager;
use WhmcsMigrate\WhmcsApi;

abstract class AbstractPhase implements PhaseInterface
{
    public function __construct(
        protected readonly Database $db,
        protected readonly WhmcsApi $api,
        protected readonly StateManager $state,
        protected readonly Logger $logger,
        protected readonly Config $config,
        protected readonly Encryptor $encryptor,
        protected readonly ExportManager $exportManager,
    ) {}

    /**
     * Whether the migration is running in dry-run mode.
     */
    protected function isDryRun(): bool
    {
        return $this->config->isDryRun();
    }

    /**
     * Whether we are exporting data from the API only (no DB writes).
     */
    protected function isExportOnly(): bool
    {
        return $this->config->isExportOnly();
    }

    /**
     * Whether we should read from exported JSONL files instead of the API.
     */
    protected function isFromExport(): bool
    {
        return $this->config->isFromExport();
    }

    /**
     * Number of records to process per batch.
     */
    protected function getBatchSize(): int
    {
        return $this->config->getBatchSize();
    }

    /**
     * Get the state key for this phase (e.g., "phase_1").
     */
    public function getPhaseKey(): string
    {
        return 'phase_' . $this->getPhaseNumber();
    }

    /**
     * Whether this phase has already been completed and should be skipped.
     */
    public function shouldSkip(): bool
    {
        return $this->state->isPhaseComplete($this->getPhaseKey());
    }

    /**
     * Mark this phase as started in the state manager.
     */
    protected function markStarted(): void
    {
        $this->state->setProgress($this->getPhaseKey(), 'in_progress');
    }

    /**
     * Mark this phase as complete in the state manager.
     */
    protected function markComplete(int $count, int $errors): void
    {
        $this->state->setProgress($this->getPhaseKey(), 'complete', 0, $count, $errors);
    }

    /**
     * Log that an entity was skipped during migration.
     */
    protected function logSkipped(string $entity, string $reason): void
    {
        $this->logger->warning("Skipped {$entity}: {$reason}");
    }
}
