<?php

namespace App\Models\HR;

use App\Models\Tenants\Tenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class LeavePolicy extends Model
{
    protected $table = 'leave_policies';

    protected $fillable = [
        'tenant_id',
        'standard_type',
        'fiscal_start_month',
        'fiscal_start_day',
        'default_annual_leave',
        'additional_leave_per_year',
        'max_annual_leave',
        'carry_over_enabled',
        'carry_over_max_days',
        'carry_over_expiry_months',
    ];

    protected $casts = [
        'tenant_id' => 'int',
        'fiscal_start_month' => 'int',
        'fiscal_start_day' => 'int',
        'default_annual_leave' => 'int',
        'additional_leave_per_year' => 'int',
        'max_annual_leave' => 'int',
        'carry_over_enabled' => 'boolean',
        'carry_over_max_days' => 'int',
        'carry_over_expiry_months' => 'int',
    ];

    public const STANDARD_TYPE_MAP = [
        'fiscal' => '회계연도',
        'hire' => '입사일',
    ];

    // =========================================================================
    // 관계
    // =========================================================================

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

    // =========================================================================
    // Accessor
    // =========================================================================

    public function getStandardTypeLabelAttribute(): string
    {
        return self::STANDARD_TYPE_MAP[$this->standard_type] ?? $this->standard_type;
    }

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

    public function scopeForTenant($query, ?int $tenantId = null)
    {
        $tenantId = $tenantId ?? session('selected_tenant_id');
        if ($tenantId) {
            return $query->where($this->table.'.tenant_id', $tenantId);
        }

        return $query;
    }
}
