<?php

namespace App\Components\Solicitor;

use App\Models\Solicitor\Solicitor;
use App\Services\HistoryService;
use Livewire\Component;

class Create extends Component {
    public $name = '';
    public $domain = '';
    public $email_address = '';
    public $phone_number = '';

    public function mount(): void {
        $this->authorize('solicitors.create');
    }

    public function save(HistoryService $history) {
        $this->authorize('solicitors.create');
        $this->validate();

        $solicitor = Solicitor::create([
            'name' => $this->name,
            'domain' => $this->domain,
            'email_address' => $this->email_address,
            'phone_number' => $this->phone_number,
        ]);

        $history->add($solicitor, 'Solicitor created', [
            'name'   => $solicitor->name,
            'domain' => $solicitor->domain,
        ]);

        $this->reset();
    }

    public function render() {
        return view('components.solicitor.create');
    }

    protected function rules() {
        return [
            'name' => ['required', 'string', 'max:255'],
            'domain' => ['nullable', 'string', 'max:255'],
            'email_address' => ['nullable', 'email', 'max:255'],
            'phone_number' => ['nullable', 'string', 'max:50'],
        ];
    }
}
