<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class OnCallShift extends Model
{
    protected $fillable = [
        'user_id', 'starts_at', 'ends_at', 'rotation_name', 'is_override',
    ];

    protected $casts = [
        'starts_at' => 'datetime',
        'ends_at' => 'datetime',
        'is_override' => 'boolean',
    ];

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

    /**
     * Returns the user currently on call (if any). Overrides take priority
     * over scheduled rotations when both are active simultaneously.
     */
    public static function current(?string $rotation = 'primary'): ?User
    {
        $now = now();
        $shift = static::where('starts_at', '<=', $now)
            ->where('ends_at', '>=', $now)
            ->when($rotation, fn ($q) => $q->where('rotation_name', $rotation))
            ->orderByDesc('is_override')   // overrides win
            ->orderBy('starts_at')
            ->first();

        return $shift?->user;
    }
}
