<?php

namespace App\Http\Controllers\Meet;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Meet\Concerns\ScopesToAccount;
use App\Models\WebhookEndpoint;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class WebhookSettingsController extends Controller
{
    use ScopesToAccount;

    public function index(Request $request): View
    {
        $this->authorizeAbility($request, 'webhooks.manage');
        $organization = $this->organization($request);

        $endpoints = WebhookEndpoint::where('organization_id', $organization->id)
            ->orderByDesc('created_at')
            ->get();

        return view('meet.settings.webhooks', [
            'organization' => $organization,
            'endpoints' => $endpoints,
            'events' => config('meet.webhook_events'),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $this->authorizeAbility($request, 'webhooks.manage');
        $organization = $this->organization($request);

        $validated = $request->validate([
            'url' => ['required', 'url', 'max:500'],
            'secret' => ['nullable', 'string', 'max:255'],
            'events' => ['required', 'array'],
            'events.*' => ['string'],
        ]);

        WebhookEndpoint::create([
            'owner_ref' => $this->ownerRef($request),
            'organization_id' => $organization->id,
            'url' => $validated['url'],
            'secret' => $validated['secret'] ?? null,
            'events' => $validated['events'],
            'is_active' => true,
        ]);

        return redirect()->route('meet.settings.webhooks')->with('success', 'Webhook endpoint added.');
    }

    public function destroy(Request $request, WebhookEndpoint $webhook): RedirectResponse
    {
        $this->authorizeAbility($request, 'webhooks.manage');
        abort_unless($webhook->organization_id === $this->organization($request)->id, 403);
        $webhook->delete();

        return redirect()->route('meet.settings.webhooks')->with('success', 'Webhook removed.');
    }
}
