<?php

namespace App\Models\Solicitor;

use App\Contracts\Communications\CommunicationSender;
use App\Enum\Contact\MessageChannel;
use App\Enum\Contact\MessageDirection;
use App\Models\Contact\Hub\ContactMessage;
use App\Trait\BelongsToSolicitor;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class SolicitorEmailSender extends Model implements CommunicationSender
{
    use BelongsToSolicitor;

    protected $table = 'solicitor_email_senders';

    protected $fillable = [
        'solicitor_id',
        'display_name',
        'email_address',
        'purpose',
        'is_default',
        'signature',
        'signature_text',
        'reply_to_email',
    ];

    protected $casts = [
        'is_default' => 'boolean',
    ];

    public function solicitor()
    {
        return $this->belongsTo(Solicitor::class);
    }

    public function inboundMessages(): HasMany
    {
        return $this->hasMany(ContactMessage::class, 'sender_email_id')
            ->where('direction', MessageDirection::INBOUND->value);
    }

    // --- CommunicationSender contract ---

    public function id(): int
    {
        return (int) $this->attributes['id'];
    }

    public function label(): string
    {
        $name = $this->display_name ?: $this->email_address;
        return "{$name} <{$this->email_address}>";
    }

    public function value(): string
    {
        return (string) $this->email_address;
    }

    public function channel(): MessageChannel
    {
        return MessageChannel::EMAIL;
    }

    public function replyTo(): ?string
    {
        return $this->reply_to_email ?? null;
    }

    public function signatureHtml(): ?string
    {
        if ($this->signature) {
            return $this->signature;
        }

        // Fallback to the firm-wide signature on the parent Solicitor.
        return $this->solicitor?->signatureHtml();
    }

    public function signatureText(): ?string
    {
        if ($this->signature_text) {
            return $this->signature_text;
        }

        if ($this->signature) {
            // Derive text from this sender's HTML signature.
            $html = preg_replace('/<br\s*\/?>/i', "\n", $this->signature);
            $html = preg_replace('/<\/p>/i', "\n\n", $html);
            return trim(strip_tags($html));
        }

        // Fallback to the firm-wide text signature on the parent Solicitor.
        return $this->solicitor?->signatureText();
    }

    public function providerConfig(): array
    {
        return [
            'purpose' => $this->purpose,
            'display_name' => $this->display_name,
        ];
    }
}
