<?php

namespace Daylight\Core\Console;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Str;

class ScoutImportCommand extends Command
{
    protected $signature = 'daylight:scout:import {model? : Model key from config or FQCN} {--all : Import all configured models that are searchable}';

    protected $description = 'Import Laravel Scout indexes using Daylight model bindings';

    public function handle(): int
    {
        if ($this->option('all')) {
            return $this->importAll();
        }

        $modelInput = $this->argument('model');

        if (! $modelInput) {
            $this->error('Please provide a {model} argument or use --all.');

            return self::INVALID;
        }

        $fqcn = $this->resolveModelClass($modelInput);

        if (! $fqcn) {
            $this->error("Unable to resolve model: {$modelInput}");

            return self::INVALID;
        }

        return $this->runScoutImport($fqcn);
    }

    protected function importAll(): int
    {
        $models = (array) config('daylight.models', []);
        $exitCode = self::SUCCESS;

        foreach ($models as $key => $class) {
            $fqcn = $this->resolveModelClass($key);
            if (! $fqcn) {
                $this->warn("Skipping unresolvable model key: {$key}");

                continue;
            }

            if (! $this->isScoutSearchable($fqcn)) {
                $this->line("Skipping non-searchable model: {$fqcn}");

                continue;
            }

            $code = $this->runScoutImport($fqcn);
            if ($code !== self::SUCCESS) {
                $exitCode = $code;
            }
        }

        return $exitCode;
    }

    protected function runScoutImport(string $fqcn): int
    {
        $this->info("Importing Scout index for {$fqcn}...");

        return Artisan::call('scout:import', [
            'model' => $fqcn,
        ]);
    }

    protected function resolveModelClass(string $input): ?string
    {
        // If an FQCN was provided and exists, return it immediately
        if (class_exists($input)) {
            return $input;
        }

        // Normalize config key (e.g. Product => product, shippingClass => shipping_class)
        $normalized = Str::snake(class_basename($input));

        $configured = config("daylight.models.{$normalized}");

        if (is_string($configured) && class_exists($configured)) {
            return $configured;
        }

        // Fallback to helper if available
        if (function_exists('daylightModel')) {
            $resolved = daylightModel($normalized);

            return class_exists($resolved) ? $resolved : null;
        }

        return null;
    }

    protected function isScoutSearchable(string $fqcn): bool
    {
        if (! class_exists($fqcn)) {
            return false;
        }

        $traits = class_uses_recursive($fqcn);

        return in_array(\Laravel\Scout\Searchable::class, $traits, true);
    }
}
