<?php

namespace App\Services;

use App\Models\Tenants\AttendanceSetting;
use App\Models\Tenants\WorkSetting;

class WorkSettingService extends Service
{
    /**
     * 근무 설정 조회 (없으면 생성)
     */
    public function getWorkSetting(): WorkSetting
    {
        $tenantId = $this->tenantId();

        $setting = WorkSetting::query()
            ->where('tenant_id', $tenantId)
            ->first();

        if (! $setting) {
            $setting = WorkSetting::create([
                'tenant_id' => $tenantId,
                'work_days' => WorkSetting::DEFAULT_WORK_DAYS,
            ]);
        }

        return $setting;
    }

    /**
     * 근무 설정 수정
     */
    public function updateWorkSetting(array $data): WorkSetting
    {
        $tenantId = $this->tenantId();

        $setting = WorkSetting::query()
            ->where('tenant_id', $tenantId)
            ->first();

        if (! $setting) {
            $setting = new WorkSetting(['tenant_id' => $tenantId]);
        }

        $setting->fill($data);
        $setting->save();

        return $setting->fresh();
    }

    /**
     * 출퇴근 설정 조회 (없으면 생성)
     */
    public function getAttendanceSetting(): AttendanceSetting
    {
        $tenantId = $this->tenantId();

        $setting = AttendanceSetting::query()
            ->where('tenant_id', $tenantId)
            ->first();

        if (! $setting) {
            $setting = AttendanceSetting::create([
                'tenant_id' => $tenantId,
            ]);
        }

        return $setting;
    }

    /**
     * 출퇴근 설정 수정
     */
    public function updateAttendanceSetting(array $data): AttendanceSetting
    {
        $tenantId = $this->tenantId();

        $setting = AttendanceSetting::query()
            ->where('tenant_id', $tenantId)
            ->first();

        if (! $setting) {
            $setting = new AttendanceSetting(['tenant_id' => $tenantId]);
        }

        $setting->fill($data);
        $setting->save();

        return $setting->fresh();
    }
}
