<?php

declare(strict_types=1);

namespace App\Services;

use App\Core\Auth;
use App\Models\DocumentMailDelivery;

final class DocumentMailHistoryService extends BaseService
{
    public function __construct(
        private readonly DocumentMailDelivery $deliveries =
            new DocumentMailDelivery()
    ) {
    }

    /** @return array<string,mixed>|null */
    public function last(string $type, int $documentId): ?array
    {
        if ($documentId <= 0) {
            return null;
        }

        return $this->deliveries->find($type, $documentId);
    }

    public function record(
        string $type,
        int $documentId,
        string $number,
        string $recipient,
        string $subject
    ): void {
        $this->deliveries->save([
            'type_document' => strtoupper(trim($type)),
            'document_id' => $documentId,
            'numero_document' => $number,
            'destinataire' => $recipient,
            'objet' => $subject,
            'envoye_par_id' => Auth::id(),
            'envoye_par_nom' => Auth::name() ?: 'Utilisateur',
            'date_envoi' => date('Y-m-d H:i:s'),
        ]);
    }
}
