<?php

namespace App\Models\Tenants;

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

/**
 * 휴가 신청 모델
 *
 * @property int $id
 * @property int $tenant_id
 * @property int $user_id
 * @property string $leave_type
 * @property string $start_date
 * @property string $end_date
 * @property float $days
 * @property string|null $reason
 * @property string $status
 * @property int|null $approved_by
 * @property string|null $approved_at
 * @property string|null $reject_reason
 * @property int|null $created_by
 * @property int|null $updated_by
 * @property int|null $deleted_by
 */
class Leave extends Model
{
    use Auditable, BelongsToTenant, SoftDeletes;

    protected $table = 'leaves';

    protected $casts = [
        'start_date' => 'date',
        'end_date' => 'date',
        'days' => 'decimal:1',
        'approved_at' => 'datetime',
    ];

    protected $fillable = [
        'tenant_id',
        'user_id',
        'leave_type',
        'start_date',
        'end_date',
        'days',
        'reason',
        'status',
        'approved_by',
        'approved_at',
        'approval_id',
        'reject_reason',
        'created_by',
        'updated_by',
        'deleted_by',
    ];

    protected $attributes = [
        'status' => 'pending',
    ];

    // =========================================================================
    // 상수 정의
    // =========================================================================

    public const TYPE_ANNUAL = 'annual';         // 연차

    public const TYPE_HALF_AM = 'half_am';       // 오전반차

    public const TYPE_HALF_PM = 'half_pm';       // 오후반차

    public const TYPE_SICK = 'sick';             // 병가

    public const TYPE_FAMILY = 'family';         // 경조사

    public const TYPE_MATERNITY = 'maternity';   // 출산

    public const TYPE_PARENTAL = 'parental';     // 육아

    public const TYPE_BUSINESS_TRIP = 'business_trip';  // 출장

    public const TYPE_REMOTE = 'remote';                // 재택근무

    public const TYPE_FIELD_WORK = 'field_work';        // 외근

    public const TYPE_EARLY_LEAVE = 'early_leave';      // 조퇴

    public const TYPE_LATE_REASON = 'late_reason';      // 지각사유서

    public const TYPE_ABSENT_REASON = 'absent_reason';  // 결근사유서

    public const STATUS_PENDING = 'pending';

    public const STATUS_APPROVED = 'approved';

    public const STATUS_REJECTED = 'rejected';

    public const STATUS_CANCELLED = 'cancelled';

    public const LEAVE_TYPES = [
        self::TYPE_ANNUAL,
        self::TYPE_HALF_AM,
        self::TYPE_HALF_PM,
        self::TYPE_SICK,
        self::TYPE_FAMILY,
        self::TYPE_MATERNITY,
        self::TYPE_PARENTAL,
        self::TYPE_BUSINESS_TRIP,
        self::TYPE_REMOTE,
        self::TYPE_FIELD_WORK,
        self::TYPE_EARLY_LEAVE,
        self::TYPE_LATE_REASON,
        self::TYPE_ABSENT_REASON,
    ];

    // 그룹 상수
    public const VACATION_TYPES = [
        self::TYPE_ANNUAL, self::TYPE_HALF_AM, self::TYPE_HALF_PM,
        self::TYPE_SICK, self::TYPE_FAMILY, self::TYPE_MATERNITY, self::TYPE_PARENTAL,
    ];

    public const ATTENDANCE_REQUEST_TYPES = [
        self::TYPE_BUSINESS_TRIP, self::TYPE_REMOTE, self::TYPE_FIELD_WORK, self::TYPE_EARLY_LEAVE,
    ];

    public const REASON_REPORT_TYPES = [
        self::TYPE_LATE_REASON, self::TYPE_ABSENT_REASON,
    ];

    // 유형 → 결재양식코드 매핑
    public const FORM_CODE_MAP = [
        'annual' => 'leave', 'half_am' => 'leave', 'half_pm' => 'leave',
        'sick' => 'leave', 'family' => 'leave', 'maternity' => 'leave', 'parental' => 'leave',
        'business_trip' => 'attendance_request', 'remote' => 'attendance_request',
        'field_work' => 'attendance_request', 'early_leave' => 'attendance_request',
        'late_reason' => 'reason_report', 'absent_reason' => 'reason_report',
    ];

    // 유형 → 근태상태 매핑 (승인 시 Attendance에 반영할 상태)
    public const ATTENDANCE_STATUS_MAP = [
        'annual' => 'vacation', 'half_am' => 'vacation', 'half_pm' => 'vacation',
        'sick' => 'vacation', 'family' => 'vacation', 'maternity' => 'vacation', 'parental' => 'vacation',
        'business_trip' => 'businessTrip', 'remote' => 'remote', 'field_work' => 'fieldWork',
        'early_leave' => null,
        'late_reason' => null,
        'absent_reason' => null,
    ];

    public const STATUSES = [
        self::STATUS_PENDING,
        self::STATUS_APPROVED,
        self::STATUS_REJECTED,
        self::STATUS_CANCELLED,
    ];

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

    /**
     * 신청자
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * 승인자
     */
    public function approver(): BelongsTo
    {
        return $this->belongsTo(User::class, 'approved_by');
    }

    /**
     * 생성자
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * 수정자
     */
    public function updater(): BelongsTo
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    /**
     * 신청자 프로필 (테넌트별)
     * 주의: eager loading 시 constrain 필요
     * ->with(['userProfile' => fn($q) => $q->where('tenant_id', $tenantId)])
     */
    public function userProfile(): HasOne
    {
        return $this->hasOne(TenantUserProfile::class, 'user_id', 'user_id');
    }

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

    /**
     * 특정 상태 필터
     */
    public function scopeWithStatus($query, string $status)
    {
        return $query->where('status', $status);
    }

    /**
     * 승인 대기 중
     */
    public function scopePending($query)
    {
        return $query->where('status', self::STATUS_PENDING);
    }

    /**
     * 승인됨
     */
    public function scopeApproved($query)
    {
        return $query->where('status', self::STATUS_APPROVED);
    }

    /**
     * 특정 기간 내
     */
    public function scopeBetweenDates($query, string $startDate, string $endDate)
    {
        return $query->where(function ($q) use ($startDate, $endDate) {
            $q->whereBetween('start_date', [$startDate, $endDate])
                ->orWhereBetween('end_date', [$startDate, $endDate])
                ->orWhere(function ($q2) use ($startDate, $endDate) {
                    $q2->where('start_date', '<=', $startDate)
                        ->where('end_date', '>=', $endDate);
                });
        });
    }

    /**
     * 특정 사용자
     */
    public function scopeForUser($query, int $userId)
    {
        return $query->where('user_id', $userId);
    }

    /**
     * 특정 연도
     */
    public function scopeForYear($query, int $year)
    {
        return $query->whereYear('start_date', $year);
    }

    // =========================================================================
    // 헬퍼 메서드
    // =========================================================================

    /**
     * 수정 가능 여부
     */
    public function isEditable(): bool
    {
        return $this->status === self::STATUS_PENDING;
    }

    /**
     * 승인 가능 여부
     */
    public function isApprovable(): bool
    {
        return $this->status === self::STATUS_PENDING;
    }

    /**
     * 취소 가능 여부
     */
    public function isCancellable(): bool
    {
        return in_array($this->status, [self::STATUS_PENDING, self::STATUS_APPROVED]);
    }

    /**
     * 휴가 유형 라벨
     */
    public function getLeaveTypeLabelAttribute(): string
    {
        return match ($this->leave_type) {
            self::TYPE_ANNUAL => '연차',
            self::TYPE_HALF_AM => '오전반차',
            self::TYPE_HALF_PM => '오후반차',
            self::TYPE_SICK => '병가',
            self::TYPE_FAMILY => '경조사',
            self::TYPE_MATERNITY => '출산휴가',
            self::TYPE_PARENTAL => '육아휴직',
            self::TYPE_BUSINESS_TRIP => '출장',
            self::TYPE_REMOTE => '재택근무',
            self::TYPE_FIELD_WORK => '외근',
            self::TYPE_EARLY_LEAVE => '조퇴',
            self::TYPE_LATE_REASON => '지각사유서',
            self::TYPE_ABSENT_REASON => '결근사유서',
            default => $this->leave_type,
        };
    }

    /**
     * 상태 라벨
     */
    public function getStatusLabelAttribute(): string
    {
        return match ($this->status) {
            self::STATUS_PENDING => '승인대기',
            self::STATUS_APPROVED => '승인',
            self::STATUS_REJECTED => '반려',
            self::STATUS_CANCELLED => '취소',
            default => $this->status,
        };
    }
}
