<?php

namespace App\Models\Approvals;

use App\Models\User;
use App\Traits\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class ApprovalDelegation extends Model
{
    use BelongsToTenant, SoftDeletes;

    protected $table = 'approval_delegations';

    protected $casts = [
        'form_ids' => 'array',
        'start_date' => 'date',
        'end_date' => 'date',
        'notify_delegator' => 'boolean',
        'is_active' => 'boolean',
    ];

    protected $fillable = [
        'tenant_id',
        'delegator_id',
        'delegate_id',
        'start_date',
        'end_date',
        'form_ids',
        'notify_delegator',
        'is_active',
        'reason',
        'created_by',
    ];

    // =========================================================================
    // 관계 정의
    // =========================================================================

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

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

    // =========================================================================
    // 스코프
    // =========================================================================

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

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

    public function scopeCurrentlyActive($query)
    {
        $today = now()->toDateString();

        return $query->active()
            ->where('start_date', '<=', $today)
            ->where('end_date', '>=', $today);
    }
}
