<?php

namespace App\Components\Sms;

use App\Models\Contact\Send\SmsSend;
use App\Models\Setting\PhoneNumber;
use App\Services\ClickSendSmsService;
use Illuminate\Database\Eloquent\Model;
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): 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->body = '';
            $this->dispatch('toast', type: 'success', message: 'SMS sent.');

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

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

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