<?php

namespace App\Modules\HR\Employees\Repositories;

use App\Modules\HR\Employees\Models\EmployeeEmergencyContact;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class EmployeeEmergencyContactRepository
{
    public function listForEmployee(int $tenantId, int $employeeId): Collection
    {
        return EmployeeEmergencyContact::query()
            ->where('tenant_id', $tenantId)
            ->where('employee_id', $employeeId)
            ->orderByDesc('is_primary')
            ->orderBy('full_name')
            ->get();
    }

    public function findForEmployee(int $tenantId, int $employeeId, int $id): ?EmployeeEmergencyContact
    {
        return EmployeeEmergencyContact::query()
            ->where('tenant_id', $tenantId)
            ->where('employee_id', $employeeId)
            ->whereKey($id)
            ->first();
    }

    /** @param  array<string, mixed>  $data */
    public function create(array $data): EmployeeEmergencyContact
    {
        return EmployeeEmergencyContact::query()->create($data);
    }

    /** @param  array<string, mixed>  $data */
    public function update(EmployeeEmergencyContact $contact, array $data): EmployeeEmergencyContact
    {
        $contact->update($data);

        return $contact->fresh();
    }

    public function delete(EmployeeEmergencyContact $contact): void
    {
        $contact->delete();
    }

    public function clearPrimary(int $employeeId): void
    {
        EmployeeEmergencyContact::query()
            ->where('employee_id', $employeeId)
            ->update(['is_primary' => false]);
    }

    public function createPrimaryAware(array $data): EmployeeEmergencyContact
    {
        return DB::transaction(function () use ($data) {
            if (! empty($data['is_primary'])) {
                $this->clearPrimary((int) $data['employee_id']);
            }

            return $this->create($data);
        });
    }

    public function updatePrimaryAware(EmployeeEmergencyContact $contact, array $data): EmployeeEmergencyContact
    {
        return DB::transaction(function () use ($contact, $data) {
            if (! empty($data['is_primary'])) {
                $this->clearPrimary((int) $contact->employee_id);
            }

            return $this->update($contact, $data);
        });
    }
}
