<?php

namespace App\Models;

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

class OrderAreaPresence extends Model
{
    use HasFactory;

    protected $table = 'order_area_presences';

    protected $fillable = [
        'orden_lavanderia_id',
        'area_id',
        'status',
        'started_at',
        'started_by_user_id',
        'completed_at',
        'completed_by_user_id',
        'load_type_id',
    ];

    protected $casts = [
        'started_at' => 'datetime',
        'completed_at' => 'datetime',
    ];

    public const STATUS_PENDING = 'pending';
    public const STATUS_IN_PROGRESS = 'in_progress';
    public const STATUS_COMPLETED = 'completed';
    public const STATUS_SKIPPED = 'skipped';

    public function ordenLavanderia(): BelongsTo
    {
        return $this->belongsTo(OrdenLavanderia::class, 'orden_lavanderia_id');
    }

    public function area(): BelongsTo
    {
        return $this->belongsTo(Area::class, 'area_id');
    }

    public function loadType(): BelongsTo
    {
        return $this->belongsTo(LoadType::class, 'load_type_id');
    }

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

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

    /**
     * Filas activas en un área (pendiente o en curso).
     */
    public function scopeActiveInArea($query, int $areaId)
    {
        return $query->where('area_id', $areaId)
            ->whereIn('status', [self::STATUS_PENDING, self::STATUS_IN_PROGRESS]);
    }

    /**
     * Presencias de una orden con estado “abierto” (no completado ni omitido).
     */
    public function scopeOpenForOrder($query, int $ordenLavanderiaId)
    {
        return $query->where('orden_lavanderia_id', $ordenLavanderiaId)
            ->whereIn('status', [self::STATUS_PENDING, self::STATUS_IN_PROGRESS]);
    }

    public function scopeForOrder($query, int $ordenLavanderiaId)
    {
        return $query->where('orden_lavanderia_id', $ordenLavanderiaId);
    }

    /**
     * @param  string|array<int, string>  $status
     */
    public function scopeWithStatus($query, $status)
    {
        return is_array($status)
            ? $query->whereIn('status', $status)
            : $query->where('status', $status);
    }
}
