<?php

namespace App\Modules\HR\Overtime\Services;

use App\Modules\HR\Overtime\Models\OvertimeRatePolicy;
use App\Modules\HR\Overtime\Repositories\OvertimeRatePolicyRepository;
use Illuminate\Support\Facades\DB;

class OvertimeRatePolicyService
{
    public function __construct(
        private readonly OvertimeRatePolicyRepository $policies,
    ) {}

    /**
     * @param  array<string, mixed>  $data
     */
    public function create(int $tenantId, array $data): OvertimeRatePolicy
    {
        return DB::transaction(function () use ($tenantId, $data): OvertimeRatePolicy {
            $data['tenant_id'] = $tenantId;
            $data['is_default'] = (bool) ($data['is_default'] ?? false);
            $data['is_active'] = (bool) ($data['is_active'] ?? true);

            $row = $this->policies->create($data);

            if ($row->is_default) {
                $this->policies->clearDefaultForTenant($tenantId, (int) $row->id);
            }

            return $row->fresh();
        });
    }

    /**
     * @param  array<string, mixed>  $data
     */
    public function update(OvertimeRatePolicy $policy, array $data): OvertimeRatePolicy
    {
        return DB::transaction(function () use ($policy, $data): OvertimeRatePolicy {
            $data['is_default'] = (bool) ($data['is_default'] ?? false);
            $data['is_active'] = (bool) ($data['is_active'] ?? $policy->is_active);

            $updated = $this->policies->update($policy, $data);

            if ($updated->is_default) {
                $this->policies->clearDefaultForTenant((int) $updated->tenant_id, (int) $updated->id);
            }

            return $updated->fresh();
        });
    }

    public function deactivate(OvertimeRatePolicy $policy): OvertimeRatePolicy
    {
        return $this->policies->update($policy, ['is_active' => false]);
    }

    public function reactivate(OvertimeRatePolicy $policy): OvertimeRatePolicy
    {
        return $this->policies->update($policy, ['is_active' => true]);
    }
}
