<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\MessengerSettingResource;
use App\Models\MessengerSetting;
use App\Support\AccessControl;
use App\Support\MessengerAccess;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;

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

        $settings = MessengerSetting::query()->first();
        if (! $settings) {
            $settings = new MessengerSetting([
                'provider' => 'telegram',
                'is_active' => false,
                'allowed_operator_ids' => [],
                'auto_create_contact' => true,
                'new_contact_action' => 'none',
                'new_contact_action_user_id' => null,
                'webhook_secret' => Str::random(40),
            ]);
        }

        return MessengerSettingResource::make($settings);
    }

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

        $providerValues = array_keys(MessengerAccess::providerOptions());
        $newContactActionValues = array_keys(MessengerAccess::newContactActionOptions());
        $validated = $request->validate([
            'provider' => ['required', Rule::in($providerValues)],
            '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'],
            'allowed_operator_ids' => ['nullable', 'array'],
            'allowed_operator_ids.*' => ['integer', 'exists:users,id'],
            'auto_create_contact' => ['nullable', 'boolean'],
            'new_contact_action' => ['required', Rule::in($newContactActionValues)],
            'new_contact_action_user_id' => ['nullable', 'integer', 'exists:users,id'],
            'webhook_secret' => ['nullable', 'string', 'max:255'],
        ]);

        $payload = [
            'provider' => MessengerAccess::normalizeProvider($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),
            'allowed_operator_ids' => MessengerAccess::sanitizeOperatorIds($validated['allowed_operator_ids'] ?? null),
            'auto_create_contact' => $request->boolean('auto_create_contact', true),
            'new_contact_action' => (string) $validated['new_contact_action'],
            'new_contact_action_user_id' => $validated['new_contact_action_user_id'] ?? null,
            'webhook_secret' => $this->nullableText($validated['webhook_secret'] ?? null),
        ];

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

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

        return MessengerSettingResource::make($settings);
    }

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

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