<?php

namespace App\Livewire;

use App\Livewire\Concerns\ResolvesCustomer;
use App\Models\SupportRequest;
use Illuminate\Validation\Rule;
use LivewireUI\Modal\ModalComponent;

/**
 * Raise a support request.
 *
 * The customer is asked for three things and nothing else: what it is about,
 * a subject, and the question. Everything an operator would otherwise have to
 * ask for — which customer, which instance, which plan — the system already
 * knows and attaches itself. Making somebody describe their own server back to
 * the people who built it is the part of support that annoys people most.
 */
class NewSupportRequest extends ModalComponent
{
    use ResolvesCustomer;

    public string $category = 'technical';

    public string $subject = '';

    public string $body = '';

    public function save()
    {
        $customer = $this->requireCustomer();

        if ($customer === null) {
            return $this->closeModal();
        }

        $data = $this->validate([
            'category' => ['required', Rule::in(SupportRequest::CATEGORIES)],
            'subject' => 'required|string|min:3|max:150',
            'body' => 'required|string|min:10|max:5000',
        ]);

        $instance = $customer->instances()
            ->whereIn('status', ['active', 'cancellation_scheduled'])
            ->latest('id')
            ->first()
            ?? $customer->instances()->latest('id')->first();

        SupportRequest::create([
            'customer_id' => $customer->id,
            'instance_id' => $instance?->id,
            'subject' => $data['subject'],
            'category' => $data['category'],
            'body' => $data['body'],
            'status' => 'open',
            // The person, not the account: on a shared login the account name
            // says nothing about who is actually asking.
            'reported_by' => auth()->user()?->name ?: auth()->user()?->email,
        ]);

        $this->dispatch('notify', message: __('support.sent'));

        return $this->redirectRoute('support', navigate: true);
    }

    public function render()
    {
        return view('livewire.new-support-request', [
            'categories' => SupportRequest::CATEGORIES,
        ]);
    }
}
