<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\TelephonySettingResource;
use App\Models\TelephonySetting;
use App\Support\AccessControl;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class TelephonySettingsController extends Controller
{
    public function show(Request $request): TelephonySettingResource
    {
        $user = $request->user();
        abort_unless(AccessControl::allows($user, 'telephony', 'read'), 403);

        $settings = TelephonySetting::query()->first();
        if (! $settings) {
            $settings = new TelephonySetting([
                'provider' => 'manual',
                'is_active' => false,
                'webhook_secret' => Str::random(40),
            ]);
        }

        return TelephonySettingResource::make($settings);
    }

    public function update(Request $request): TelephonySettingResource
    {
        $user = $request->user();
        abort_unless(AccessControl::allows($user, 'telephony', 'update'), 403);

        $validated = $request->validate([
            'provider' => ['required', 'string', 'max:60'],
            'is_active' => ['nullable', 'boolean'],
            'api_base_url' => ['nullable', 'string', 'max:255'],
            'api_key' => ['nullable', 'string', 'max:255'],
            'api_secret' => ['nullable', 'string', 'max:255'],
            'account_id' => ['nullable', 'string', 'max:255'],
            'inbound_number' => ['nullable', 'string', 'max:60'],
            'outbound_number' => ['nullable', 'string', 'max:60'],
            'webhook_secret' => ['nullable', 'string', 'max:255'],
        ]);

        $payload = [
            'provider' => trim((string) $validated['provider']),
            'is_active' => $request->boolean('is_active'),
            'api_base_url' => $this->nullableText($validated['api_base_url'] ?? null),
            'api_key' => $this->nullableText($validated['api_key'] ?? null),
            'api_secret' => $this->nullableText($validated['api_secret'] ?? null),
            'account_id' => $this->nullableText($validated['account_id'] ?? null),
            'inbound_number' => $this->nullableText($validated['inbound_number'] ?? null),
            'outbound_number' => $this->nullableText($validated['outbound_number'] ?? null),
            'webhook_secret' => $this->nullableText($validated['webhook_secret'] ?? null),
        ];

        if (($payload['webhook_secret'] ?? '') === '') {
            $payload['webhook_secret'] = TelephonySetting::query()->value('webhook_secret') ?: Str::random(40);
        }

        $settings = TelephonySetting::query()->first() ?? new TelephonySetting();
        $settings->fill($payload)->save();

        return TelephonySettingResource::make($settings);
    }

    private function nullableText(mixed $value): ?string
    {
        $value = trim((string) $value);

        return $value === '' ? null : $value;
    }
}
