<?php

namespace App\Console\Commands;

use App\Models\Dealer;
use Illuminate\Console\Command;

class InitDefaultDealerBranding extends Command
{
    protected $signature = 'mtt:dealer-branding:init-default
                            {--overwrite : Overwrite existing branding fields on the default dealer}';

    protected $description = 'Initialize branding fields on the default dealer to match the current MTT shell exactly.';

    public function handle(): int
    {
        /** @var Dealer|null $defaultDealer */
        $defaultDealer = Dealer::query()->where('is_default', true)->first();

        if (! $defaultDealer) {
            $this->error('No default dealer found (is_default = true). Aborting.');

            return 1;
        }

        $overwrite = (bool) $this->option('overwrite');

        // Tailwind v3.1.0 defaults used by the current shell:
        // bg-neutral-800 => #262626
        // bg-red-600     => #dc2626
        // bg-gray-100    => #f3f4f6
        $desired = [
            'logo_path' => 'images/mega-theron-logo.png',
            // Leave favicon_path null to keep platform fallback (/public/favicon.ico).
            'favicon_path' => null,

            'nav_color' => '#262626',
            'accent_color' => '#dc2626',
            'accent_color_2' => '#262626',
            'background_color' => '#f3f4f6',
            'topbar_color' => '#ffffff',
        ];

        $updates = [];
        foreach ($desired as $field => $value) {
            if ($overwrite) {
                $updates[$field] = $value;
                continue;
            }

            $current = $defaultDealer->getAttribute($field);
            $isEmpty = $current === null || (is_string($current) && trim($current) === '');
            if ($isEmpty) {
                $updates[$field] = $value;
            }
        }

        if (empty($updates)) {
            $this->info('Default dealer already has branding fields set. Nothing to do.');

            return 0;
        }

        $defaultDealer->fill($updates);
        $defaultDealer->save();

        $this->info(sprintf(
            'Initialized default dealer branding for [ID %d] %s (%s).',
            $defaultDealer->id,
            $defaultDealer->name,
            $defaultDealer->code ?? 'NO-CODE'
        ));

        foreach ($updates as $key => $val) {
            $display = $val === null ? 'NULL' : (string) $val;
            $this->line("  - {$key}: {$display}");
        }

        return 0;
    }
}

