<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Schema;

class Badge extends Model
{
    public const SEVEN_DAY_JOURNAL = 'seven_day_journal';
    public const THIRTY_DAY_DISCIPLINE = 'thirty_day_discipline';
    public const RISK_MANAGER = 'risk_manager';
    public const CONSISTENT_TRADER = 'consistent_trader';

    protected $fillable = [
        'name',
        'description',
        'icon',
        'requirement_key',
        'requirement',
        'is_active',
        'sort_order',
    ];

    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
            'sort_order' => 'integer',
        ];
    }

    /**
     * @return array<int,array<string,mixed>>
     */
    public static function defaults(): array
    {
        return [
            ['name' => '7-Day Journal Badge', 'description' => 'Awarded after journaling seven challenge days.', 'icon' => '7', 'requirement_key' => self::SEVEN_DAY_JOURNAL, 'requirement' => 'Complete 7 journal days.', 'sort_order' => 1],
            ['name' => '30-Day Discipline Badge', 'description' => 'Awarded after completing thirty journal days.', 'icon' => '30', 'requirement_key' => self::THIRTY_DAY_DISCIPLINE, 'requirement' => 'Complete 30 journal days.', 'sort_order' => 2],
            ['name' => 'Risk Manager Badge', 'description' => 'Awarded for consistent stop loss and take profit planning.', 'icon' => 'risk', 'requirement_key' => self::RISK_MANAGER, 'requirement' => 'Journal at least 10 trades with stop loss and take profit.', 'sort_order' => 3],
            ['name' => 'Consistent Trader Badge', 'description' => 'Awarded for a strong active journaling streak.', 'icon' => 'streak', 'requirement_key' => self::CONSISTENT_TRADER, 'requirement' => 'Build a 10-day journaling streak.', 'sort_order' => 4],
        ];
    }

    public static function seedDefaults(): void
    {
        if (! Schema::hasTable('badges')) {
            return;
        }

        foreach (self::defaults() as $default) {
            self::query()->firstOrCreate(['name' => $default['name']], $default + ['is_active' => true]);
        }
    }

    /**
     * @return Collection<int,self>
     */
    public static function activeOrdered(): Collection
    {
        if (! Schema::hasTable('badges')) {
            return collect(self::defaults())
                ->map(fn (array $default): self => new self($default + ['is_active' => true]));
        }

        self::seedDefaults();

        return self::query()
            ->where('is_active', true)
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get();
    }
}
