<?php

namespace App\Components\Contact\Admin;

use App\Actions\Communications\ValidateRecipientAction;
use App\Enum\Contact\MessageChannel;
use App\Models\RedressScheme;
use App\Models\Solicitor\Solicitor;
use Livewire\Component;

class CommunicationsSettings extends Component
{
    public string $schemeContactName = '';
    public string $schemeEmail = '';
    public string $schemePhone = '';

    public ?string $success = null;
    public ?string $error = null;

    public function mount(): void
    {
        $this->authorize('communications.settings.manage');
        $this->loadScheme();
    }

    public function saveScheme(): void
    {
        $this->authorize('communications.settings.manage');

        $this->validate([
            'schemeEmail' => 'nullable|email|max:255',
            'schemePhone' => 'nullable|string|max:50',
            'schemeContactName' => 'nullable|string|max:255',
        ]);

        RedressScheme::updateOrCreate([], [
            'contact_name' => $this->schemeContactName ?: null,
            'email'        => $this->schemeEmail ?: null,
            'phone'        => $this->schemePhone ?: null,
        ]);

        $this->success = 'Scheme contact details saved.';
        $this->error = null;
    }

    public function render()
    {
        $scheme = RedressScheme::first();

        $schemeValidity = $scheme
            ? app(ValidateRecipientAction::class)(MessageChannel::EMAIL, $scheme, app(Solicitor::class))
            : null;

        return view('components.contact.admin.communications-settings', [
            'scheme'         => $scheme,
            'schemeValidity' => $schemeValidity,
        ]);
    }

    private function loadScheme(): void
    {
        $scheme = RedressScheme::first();
        $this->schemeContactName = $scheme?->contact_name ?? '';
        $this->schemeEmail       = $scheme?->getRawOriginal('email') ?? '';
        $this->schemePhone       = $scheme?->getRawOriginal('phone') ?? '';
    }
}
