<?php

namespace App\Components\Sms;

use App\Interface\HistoryOwner;
use App\Models\Claim\Claim;
use App\Models\Contact\Send\SmsSend;
use App\Models\Setting\PhoneNumber;
use App\Services\ClickSendSmsService;
use App\Services\HistoryService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Livewire\Component;

class QuickTexter extends Component {
    public Model $owner;

    public string $toNumber = '';
    public string $message  = '';
    public string $body = '';

    public function mount(Model $owner, string $defaultPhone = ''): void {
        $this->owner    = $owner;
        $this->toNumber = $defaultPhone;
    }

    protected function rules(): array {
        return [
            'toNumber' => ['required', 'string', 'min:7', 'max:20'],
            'body'  => ['required', 'string', 'min:1', 'max:1224'],
        ];
    }

    public function send(ClickSendSmsService $clicksend, HistoryService $history): void {
        $this->validate();

        $to   = preg_replace('/\s+/', '', $this->toNumber);
        $from = PhoneNumber::where('is_primary', true)->value('normalized_phone_number')
            ?? config('services.clicksend.sms_from');

        $record = SmsSend::create([
            'sendable_id'   => $this->owner->getKey(),
            'sendable_type' => get_class($this->owner),
            'to_number'     => $to,
            'from_number'   => $from,
            'message'       => $this->body,
            'status'        => 'sending',
            'provider'      => 'clicksend',
        ]);

        try {
            $response = $clicksend->send(
                to:      $to,
                message: $this->body,
                from:    $from ?: null,
            );

            $message = $response['data']['messages'][0] ?? [];

            $record->update([
                'status'              => 'sent',
                'sent_at'             => now(),
                'provider_message_id' => $message['message_id'] ?? null,
                'provider_response'   => $message,
            ]);

            $this->recordHistory($history, 'SMS sent to ' . $to, [
                'sms_id'  => $record->id,
                'to'      => $to,
                'preview' => Str::limit($this->body, 120),
            ]);

            $this->body = '';
            $this->dispatch('toast', type: 'success', message: 'SMS sent.');

        } catch (\Throwable $e) {
            $record->update([
                'status'        => 'failed',
                'error_message' => $e->getMessage(),
            ]);

            $this->recordHistory($history, 'SMS to ' . $to . ' failed', [
                'sms_id' => $record->id,
                'to'     => $to,
                'error'  => $e->getMessage(),
            ]);

            $this->dispatch('toast', type: 'error', message: 'SMS failed: ' . $e->getMessage());
        }
    }

    private function recordHistory(HistoryService $history, string $event, array $context): void
    {
        if ($this->owner instanceof Claim) {
            $history->addForClaim($this->owner, $event, $context);
        } elseif ($this->owner instanceof HistoryOwner) {
            $history->add($this->owner, $event, $context);
        } else {
            $history->addForActor($event, $context);
        }
    }

    public function render(): \Illuminate\View\View {
        return view('components.sms.quick-texter', [
            'history' => $this->owner->smses()->latest()->take(5)->get(),
        ]);
    }
}
