<?php

namespace App\Domain\Attendance\Models;

use App\Domain\Attendance\Enums\AttendanceStatus;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Domain\Training\Models\TrainingSession;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;

class AttendanceRecord extends Model
{
    use BelongsToAcademy, HasUuid;

    protected $fillable = [
        'academy_id',
        'training_session_id',
        'subject_type',
        'subject_id',
        'status',
        'check_in_at',
        'check_out_at',
        'late_minutes',
        'duration_minutes',
        'notes',
        'status_reason',
        'marked_by',
        'marked_at',
        'is_auto_generated',
        'is_flagged',
        'metadata',
    ];

    protected function casts(): array
    {
        return [
            'status' => AttendanceStatus::class,
            'check_in_at' => 'datetime',
            'check_out_at' => 'datetime',
            'marked_at' => 'datetime',
            'late_minutes' => 'integer',
            'duration_minutes' => 'integer',
            'is_auto_generated' => 'boolean',
            'is_flagged' => 'boolean',
            'metadata' => 'array',
        ];
    }

    public function session(): BelongsTo
    {
        return $this->belongsTo(TrainingSession::class, 'training_session_id');
    }

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

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

    public function scopeForSession($query, int $sessionId)
    {
        return $query->where('training_session_id', $sessionId);
    }

    public function scopeExpected($query)
    {
        return $query->where('status', AttendanceStatus::Expected);
    }

    public function scopeMarked($query)
    {
        return $query->where('status', '!=', AttendanceStatus::Expected);
    }

    public function scopePositive($query)
    {
        return $query->whereIn('status', [
            AttendanceStatus::Present,
            AttendanceStatus::Late,
            AttendanceStatus::Partial,
        ]);
    }

    public function scopeNegative($query)
    {
        return $query->whereIn('status', [
            AttendanceStatus::Absent,
            AttendanceStatus::NoShow,
        ]);
    }
}
