<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;

class CommunityCategory extends Model
{
    protected $fillable = ['name', 'slug', 'description', 'is_active', 'sort_order'];

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

    public static function defaults(): array
    {
        return [
            ['name' => 'General Trading', 'description' => 'General trading discussions and helpful questions.', 'sort_order' => 1],
            ['name' => 'Trade Review', 'description' => 'Share a trade idea or completed setup for feedback.', 'sort_order' => 2],
            ['name' => 'Risk Management', 'description' => 'Position sizing, stop loss, risk/reward, and account protection.', 'sort_order' => 3],
            ['name' => 'Psychology', 'description' => 'Mindset, emotions, discipline, fear, greed, and consistency.', 'sort_order' => 4],
            ['name' => 'Strategy Discussion', 'description' => 'Discuss trading strategies and execution plans.', 'sort_order' => 5],
            ['name' => 'Beginner Questions', 'description' => 'Beginner-friendly questions and answers.', 'sort_order' => 6],
            ['name' => 'Market News', 'description' => 'Discuss market events without copying full news articles.', 'sort_order' => 7],
        ];
    }

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

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

    public static function activeOrdered(): Collection
    {
        if (! Schema::hasTable('community_categories')) {
            return collect(self::defaults())->map(fn (array $category) => new self($category + [
                'slug' => Str::slug($category['name']),
                'is_active' => true,
            ]));
        }

        self::seedDefaults();

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

    public function posts(): HasMany
    {
        return $this->hasMany(CommunityPost::class);
    }
}
