<?php

namespace App\Services;

use App\Models\Tenants\LeavePolicy;

class LeavePolicyService extends Service
{
    /**
     * 휴가 정책 조회
     * 없으면 기본값으로 생성
     */
    public function show(): LeavePolicy
    {
        $tenantId = $this->tenantId();

        $policy = LeavePolicy::where('tenant_id', $tenantId)->first();

        if (! $policy) {
            $policy = LeavePolicy::createDefault($tenantId, $this->apiUserId());
        }

        return $policy;
    }

    /**
     * 휴가 정책 업데이트
     * 없으면 생성
     */
    public function update(array $data): LeavePolicy
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        $policy = LeavePolicy::where('tenant_id', $tenantId)->first();

        if ($policy) {
            $policy->fill([
                'standard_type' => $data['standard_type'] ?? $policy->standard_type,
                'fiscal_start_month' => $data['fiscal_start_month'] ?? $policy->fiscal_start_month,
                'fiscal_start_day' => $data['fiscal_start_day'] ?? $policy->fiscal_start_day,
                'default_annual_leave' => $data['default_annual_leave'] ?? $policy->default_annual_leave,
                'additional_leave_per_year' => $data['additional_leave_per_year'] ?? $policy->additional_leave_per_year,
                'max_annual_leave' => $data['max_annual_leave'] ?? $policy->max_annual_leave,
                'carry_over_enabled' => $data['carry_over_enabled'] ?? $policy->carry_over_enabled,
                'carry_over_max_days' => $data['carry_over_max_days'] ?? $policy->carry_over_max_days,
                'carry_over_expiry_months' => $data['carry_over_expiry_months'] ?? $policy->carry_over_expiry_months,
                'updated_by' => $userId,
            ]);
            $policy->save();
        } else {
            $policy = LeavePolicy::create([
                'tenant_id' => $tenantId,
                'standard_type' => $data['standard_type'] ?? LeavePolicy::TYPE_FISCAL,
                'fiscal_start_month' => $data['fiscal_start_month'] ?? 1,
                'fiscal_start_day' => $data['fiscal_start_day'] ?? 1,
                'default_annual_leave' => $data['default_annual_leave'] ?? 15,
                'additional_leave_per_year' => $data['additional_leave_per_year'] ?? 1,
                'max_annual_leave' => $data['max_annual_leave'] ?? 25,
                'carry_over_enabled' => $data['carry_over_enabled'] ?? true,
                'carry_over_max_days' => $data['carry_over_max_days'] ?? 10,
                'carry_over_expiry_months' => $data['carry_over_expiry_months'] ?? 3,
                'created_by' => $userId,
                'updated_by' => $userId,
            ]);
        }

        return $policy->fresh();
    }
}
