<?php

namespace App\Models;

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

class DisciplineScoreRule extends Model
{
    public const STOP_LOSS = 'stop_loss';
    public const TAKE_PROFIT = 'take_profit';
    public const PSYCHOLOGY_NOTE = 'psychology_note';
    public const RISK_REWARD = 'risk_reward';
    public const AVOIDED_OVERTRADING = 'avoided_overtrading';
    public const JOURNALED_CONSISTENTLY = 'journaled_consistently';

    protected $fillable = [
        'key',
        'name',
        'points',
        'is_active',
        'sort_order',
    ];

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

    /**
     * @return array<int,array<string,mixed>>
     */
    public static function defaults(): array
    {
        return [
            ['key' => self::STOP_LOSS, 'name' => 'Stop loss added', 'points' => 20, 'sort_order' => 1],
            ['key' => self::TAKE_PROFIT, 'name' => 'Take profit added', 'points' => 20, 'sort_order' => 2],
            ['key' => self::PSYCHOLOGY_NOTE, 'name' => 'Psychology note added', 'points' => 15, 'sort_order' => 3],
            ['key' => self::RISK_REWARD, 'name' => 'Risk reward followed', 'points' => 15, 'sort_order' => 4],
            ['key' => self::AVOIDED_OVERTRADING, 'name' => 'Overtrading avoided', 'points' => 15, 'sort_order' => 5],
            ['key' => self::JOURNALED_CONSISTENTLY, 'name' => 'Trade journal consistency', 'points' => 15, 'sort_order' => 6],
        ];
    }

    public static function seedDefaults(): void
    {
        foreach (self::defaults() as $default) {
            self::query()->firstOrCreate(['key' => $default['key']], $default + ['is_active' => true]);
        }
    }

    /**
     * @return Collection<int,self>
     */
    public static function activeOrdered(): Collection
    {
        self::seedDefaults();

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