<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Committee extends Model
{
    use HasFactory, SoftDeletes;

    // =========================================================================
    // Constants
    // =========================================================================

    public const STATUS_ACTIVE = 'active';
    public const STATUS_DISSOLVED = 'dissolved';
    public const STATUS_ON_HOLD = 'on_hold';

    public const STATUSES = [
        self::STATUS_ACTIVE => 'Active',
        self::STATUS_DISSOLVED => 'Dissolved',
        self::STATUS_ON_HOLD => 'On Hold',
    ];

    // =========================================================================
    // Model Configuration
    // =========================================================================

    protected $fillable = [
        'uuid',
        'association_id',
        'name',
        'slug',
        'description',
        'mandate',
        'expected_outcome',
        'status',
        'committable_type',
        'committable_id',
        'start_date',
        'end_date',
        'created_by',
    ];

    protected $casts = [
        'start_date' => 'date',
        'end_date' => 'date',
    ];

    protected $appends = ['active_member_count', 'chairperson_name'];

    // =========================================================================
    // Boot
    // =========================================================================

    protected static function boot()
    {
        parent::boot();

        static::creating(function (Committee $committee) {
            if (!$committee->uuid) {
                $committee->uuid = (string) Str::uuid();
            }
            if (!$committee->slug && $committee->name) {
                $committee->slug = Str::slug($committee->name);
            }
        });
    }

    // =========================================================================
    // Relationships
    // =========================================================================

    public function association()
    {
        return $this->belongsTo(Association::class);
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * All committee member records (active and inactive).
     */
    public function members()
    {
        return $this->hasMany(CommitteeMember::class);
    }

    /**
     * Only active committee members.
     */
    public function activeMembers()
    {
        return $this->hasMany(CommitteeMember::class)->where('is_active', true);
    }

    /**
     * Polymorphic relationship to the linked module context.
     * Can be a Project, Event, Election, or null for general/standing committees.
     */
    public function committable()
    {
        return $this->morphTo();
    }

    /**
     * Reports submitted by the committee.
     */
    public function reports()
    {
        return $this->hasMany(CommitteeReport::class)->orderByDesc('submitted_at');
    }

    // =========================================================================
    // Accessors
    // =========================================================================

    public function getActiveMemberCountAttribute(): int
    {
        return $this->activeMembers()->count();
    }

    public function getChairpersonNameAttribute(): ?string
    {
        $chairperson = $this->activeMembers()
            ->where('role', CommitteeMember::ROLE_CHAIRPERSON)
            ->with('user')
            ->first();

        return $chairperson?->user?->name;
    }

    // =========================================================================
    // Helpers
    // =========================================================================

    /**
     * Get the chairperson member record.
     */
    public function chairperson(): ?CommitteeMember
    {
        return $this->activeMembers()
            ->where('role', CommitteeMember::ROLE_CHAIRPERSON)
            ->first();
    }

    /**
     * Get the display label for the linked context.
     */
    public function getContextLabelAttribute(): string
    {
        if (!$this->committable_type) {
            return 'General / Standing';
        }

        $type = class_basename($this->committable_type);
        $name = $this->committable?->title ?? $this->committable?->name ?? '—';

        return "{$type}: {$name}";
    }

    // =========================================================================
    // Scopes
    // =========================================================================

    public function scopeActive($query)
    {
        return $query->where('status', self::STATUS_ACTIVE);
    }

    public function scopeForProject($query, int $projectId)
    {
        return $query->where('committable_type', Project::class)
            ->where('committable_id', $projectId);
    }

    public function scopeForEvent($query, int $eventId)
    {
        return $query->where('committable_type', Event::class)
            ->where('committable_id', $eventId);
    }

    public function scopeForElection($query, int $electionId)
    {
        return $query->where('committable_type', Election::class)
            ->where('committable_id', $electionId);
    }

    public function scopeGeneral($query)
    {
        return $query->whereNull('committable_type');
    }

    public function scopeSearch($query, ?string $search)
    {
        if (!$search) return $query;

        return $query->where(function ($q) use ($search) {
            $q->where('name', 'like', "%{$search}%")
              ->orWhere('description', 'like', "%{$search}%")
              ->orWhere('mandate', 'like', "%{$search}%");
        });
    }
}
