<?php

declare(strict_types=1);

namespace App\Repositories\QzCertificate;

use App\Models\QzCertificate;

class QzCertificateRepository implements QzCertificateRepositoryInterface
{
    /**
     * Get the active certificate.
     */
    public function getActive(): ?QzCertificate
    {
        return QzCertificate::where('status', 'active')->first();
    }

    /**
     * Find a certificate by name.
     */
    public function findByName(string $name): ?QzCertificate
    {
        return QzCertificate::where('name', $name)->first();
    }

    /**
     * Create a new certificate record.
     */
    public function create(array $data): QzCertificate
    {
        return QzCertificate::create($data);
    }

    /**
     * Update an existing certificate record.
     */
    public function update(QzCertificate $certificate, array $data): bool
    {
        return $certificate->update($data);
    }

    /**
     * Delete a certificate record.
     */
    public function delete(QzCertificate $certificate): bool
    {
        return (bool) $certificate->delete();
    }

    /**
     * Mark all other certificates as inactive/deleted when a new active one is generated.
     */
    public function deactivateOthers(int $activeId): void
    {
        QzCertificate::where('id', '!=', $activeId)
            ->where('status', 'active')
            ->update(['status' => 'invalid']);
    }
}
