<?php

namespace App\Domain\Scheduling\Models;

use App\Domain\Scheduling\Enums\AssignmentScope;
use App\Domain\Scheduling\Enums\AssignmentStatus;
use App\Domain\Shared\Traits\Auditable;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class Assignment extends Model
{
    use BelongsToAcademy, HasUuid, SoftDeletes, Auditable;

    protected $fillable = [
        'academy_id',
        'user_id',
        'assignable_type',
        'assignable_id',
        'role_label',
        'scope',
        'status',
        'start_date',
        'end_date',
        'start_time',
        'end_time',
        'is_primary',
        'notes',
        'schedule_days',
        'metadata',
        'created_by',
    ];

    protected function casts(): array
    {
        return [
            'scope' => AssignmentScope::class,
            'status' => AssignmentStatus::class,
            'start_date' => 'date',
            'end_date' => 'date',
            'is_primary' => 'boolean',
            'schedule_days' => 'array',
            'metadata' => 'array',
        ];
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function assignable(): MorphTo
    {
        return $this->morphTo();
    }

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

    public function isActive(): bool
    {
        return $this->status === AssignmentStatus::Active;
    }

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

    public function scopeForUser($query, int $userId)
    {
        return $query->where('user_id', $userId);
    }

    public function scopeForGroup($query, int $groupId)
    {
        return $query->where('assignable_type', \App\Domain\Training\Models\TrainingGroup::class)
                     ->where('assignable_id', $groupId);
    }

    public function scopeForSession($query, int $sessionId)
    {
        return $query->where('assignable_type', \App\Domain\Training\Models\TrainingSession::class)
                     ->where('assignable_id', $sessionId);
    }
}
