<?php

namespace App\Repositories;

use App\Contracts\FingerprintMachineRepositoryInterface;
use App\DTO\MachineDTO;
use App\Models\FingerprintMachine;
use Illuminate\Database\Eloquent\Collection;

class FingerprintMachineRepository implements FingerprintMachineRepositoryInterface
{
    public function getAll(): Collection
    {
        return FingerprintMachine::withCount(['attendanceLogs'])->get();
    }

    public function findById(int $id): ?FingerprintMachine
    {
        return FingerprintMachine::withCount(['attendanceLogs'])->find($id);
    }

    public function create(MachineDTO $machineDTO): FingerprintMachine
    {
        return FingerprintMachine::create($machineDTO->toArray());
    }

    public function update(int $id, MachineDTO $machineDTO): FingerprintMachine
    {
        $machine = FingerprintMachine::findOrFail($id);
        $machine->update($machineDTO->toArray());

        return $machine->fresh();
    }

    public function updateStatus(FingerprintMachine $machine, string $status, ?string $lastSync = null): bool
    {
        $payload = ['status' => $status];
        if ($lastSync !== null) {
            $payload['last_sync'] = $lastSync;
        }

        return $machine->update($payload);
    }

    public function delete(int $id): bool
    {
        $machine = FingerprintMachine::findOrFail($id);
        return (bool) $machine->delete();
    }


}
