<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\Conversation;
use App\Models\Message;
use App\Models\User;

final class ConversationSystemMessageService
{
    public function record(Conversation $conversation, User $actor, string $body): Message
    {
        return Message::query()->create([
            'conversation_id' => $conversation->id,
            'sender_id' => $actor->id,
            'message' => $body,
            'is_system' => true,
        ]);
    }

    public function visitMessage(User $actor, string $visitLabel, ?string $visitDate, ?string $visitTime, ?string $locationNote): string
    {
        $name = $actor->name;
        $parts = ["L'agent « {$name} » a mis à jour la visite : {$visitLabel}."];

        if ($visitDate !== null && $visitDate !== '') {
            $parts[] = "Date : {$visitDate}".($visitTime !== null && $visitTime !== '' ? " à {$visitTime}" : '').'.';
        }

        if ($locationNote !== null && $locationNote !== '') {
            $parts[] = "Lieu / remarque : {$locationNote}.";
        }

        return implode(' ', $parts);
    }

    public function commissionMessage(User $actor, string $statusLabel, ?string $note, ?string $total): string
    {
        $name = $actor->name;
        $chunks = ["L'agent « {$name} » a mis à jour la commission : {$statusLabel}."];

        if ($total !== null && $total !== '') {
            $chunks[] = "Montant total : {$total} DT.";
        }

        if ($note !== null && $note !== '') {
            $chunks[] = "Remarque : {$note}.";
        }

        return implode(' ', $chunks);
    }

    public function offerMessage(User $actor, string $statusLabel, ?string $amount, ?string $offerDate, ?string $note): string
    {
        $name = $actor->name;
        $chunks = ["L'agent « {$name} » a mis à jour l'offre : {$statusLabel}."];

        if ($amount !== null && $amount !== '') {
            $chunks[] = "Montant : {$amount} DT.";
        }

        if ($offerDate !== null && $offerDate !== '') {
            $chunks[] = "Date de l'offre : {$offerDate}.";
        }

        if ($note !== null && $note !== '') {
            $chunks[] = "Remarque : {$note}.";
        }

        return implode(' ', $chunks);
    }

    public function closeMessage(User $actor, string $outcomeLabel, ?string $reason): string
    {
        $name = $actor->name;
        $text = "L'agent « {$name} » a clôturé l'affaire : {$outcomeLabel}.";

        if ($reason !== null && $reason !== '') {
            $text .= " Motif : {$reason}.";
        }

        return $text;
    }
}
