<?php

namespace App\Models;

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

class HomepageFeature extends Model
{
    protected $fillable = [
        'title',
        'description',
        'icon',
        '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 [
            ['title' => 'Trades', 'description' => 'Record entries, exits, sessions, screenshots, and outcomes.', 'icon' => 'chart', 'sort_order' => 1],
            ['title' => 'Mistakes', 'description' => 'Tag repeated mistakes like revenge trading, overtrading, and poor risk management.', 'icon' => 'alert', 'sort_order' => 2],
            ['title' => 'Emotions', 'description' => 'Track fear, greed, confidence, discipline, and frustration on each trade.', 'icon' => 'heart', 'sort_order' => 3],
            ['title' => 'Risk', 'description' => 'Review stop loss, take profit, risk/reward discipline, and overtrading behavior.', 'icon' => 'shield', 'sort_order' => 4],
            ['title' => 'Performance', 'description' => 'See win rate, profit/loss, best pairs, worst sessions, and trends.', 'icon' => 'trend', 'sort_order' => 5],
            ['title' => 'Discipline', 'description' => 'Use weekly and monthly discipline scores to improve habits.', 'icon' => 'target', 'sort_order' => 6],
        ];
    }

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

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

    /**
     * @return Collection<int,self>
     */
    public static function activeOrdered(): Collection
    {
        if (! Schema::hasTable('homepage_features')) {
            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('title')
            ->get();
    }
}
