<?php

declare(strict_types=1);

namespace Builder\Core\Foundation\Commands;

use Builder\Core\Models\Language;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

final class CheckCommand extends Command
{
    protected $signature = 'builder:check';

    protected $description = 'Check that the Builder installation is configured correctly';

    public function handle(): int
    {
        $this->line('');
        $this->line('<fg=cyan;options=bold>Builder Installation Check</>');
        $this->line('');

        $checks = [
            $this->check('Migrations run', $this->migrationsAreUp()),
            $this->check('Languages seeded', $this->languagesSeeded()),
            $this->check('Default language set', $this->defaultLanguageSet()),
            $this->check('Assets linked', $this->assetsLinked()),
        ];

        $this->line('');
        $this->line('  <fg=yellow>Scheduler:</> Ensure the scheduler runs: <fg=white>* * * * * php artisan schedule:run >> /dev/null 2>&1</>');
        $this->line('');

        return ! in_array(false, $checks, true) ? Command::SUCCESS : Command::FAILURE;
    }

    private function check(string $label, bool $result): bool
    {
        $icon = $result ? '<fg=green>✓</>' : '<fg=red>✗</>';
        $status = $result ? '<fg=green>OK</>' : '<fg=red>FAIL</>';

        $this->line("  {$icon}  {$label}: {$status}");

        return $result;
    }

    private function migrationsAreUp(): bool
    {
        try {
            DB::table('migrations')->count();

            return true;
        } catch (\Throwable) {
            return false;
        }
    }

    private function languagesSeeded(): bool
    {
        try {
            return Schema::hasTable('languages') && Language::query()->count() > 0;
        } catch (\Throwable) {
            return false;
        }
    }

    private function defaultLanguageSet(): bool
    {
        try {
            return Schema::hasTable('languages') && Language::allLocales()->contains('is_default', true);
        } catch (\Throwable) {
            return false;
        }
    }

    private function assetsLinked(): bool
    {
        return file_exists(public_path('vendor/builder/core'));
    }
}
