<?php

namespace App\Http\Controllers;

use App\Models\WebhookSource;
use App\Models\WebhookLog;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class WebhookSourceController extends Controller
{
    /**
     * Display a listing of webhook sources
     */
    public function index()
    {
        $webhooks = WebhookSource::withCount([
            'webhookLogs',
            'webhookLogs as success_count' => function ($query) {
                $query->where('status', 'success');
            },
            'webhookLogs as failed_count' => function ($query) {
                $query->where('status', 'failed');
            }
        ])
        ->latest()
        ->get();

        return view('stores.webhooks.index', compact('webhooks'));
    }

    /**
     * Show the form for creating a new webhook source
     */
    public function create()
    {
        return view('stores.webhooks.create');
    }

    /**
     * Store a newly created webhook source
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'nullable|string|max:100',
            'secret_key' => 'nullable|string|max:255',
            'field_mapping' => 'nullable|array',
            'settings' => 'nullable|array',
        ]);

        // Generate unique webhook token
        $validated['webhook_token'] = Str::random(32);
        $validated['type'] = $validated['type'] ?? 'generic';
        $validated['is_active'] = true;

        $webhook = WebhookSource::create($validated);

        return redirect()
            ->route('stores.webhooks.show', $webhook)
            ->with('success', 'Webhook source created successfully!');
    }

    /**
     * Display the specified webhook source with recent logs
     */
    public function show(WebhookSource $webhook)
    {
        $webhook->loadCount([
            'webhookLogs',
            'webhookLogs as success_count' => function ($query) {
                $query->where('status', 'success');
            },
            'webhookLogs as failed_count' => function ($query) {
                $query->where('status', 'failed');
            }
        ]);

        // Get recent logs
        $recentLogs = $webhook->webhookLogs()
            ->with('order')
            ->latest()
            ->limit(50)
            ->get();

        return view('stores.webhooks.show', compact('webhook', 'recentLogs'));
    }

    /**
     * Show the form for editing the webhook source
     */
    public function edit(WebhookSource $webhook)
    {
        return view('stores.webhooks.edit', compact('webhook'));
    }

    /**
     * Update the specified webhook source
     */
    public function update(Request $request, WebhookSource $webhook)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'nullable|string|max:100',
            'secret_key' => 'nullable|string|max:255',
            'field_mapping' => 'nullable|array',
            'settings' => 'nullable|array',
        ]);

        $webhook->update($validated);

        return redirect()
            ->route('stores.webhooks.show', $webhook)
            ->with('success', 'Webhook source updated successfully!');
    }

    /**
     * Remove the specified webhook source
     */
    public function destroy(WebhookSource $webhook)
    {
        $webhook->delete();

        return redirect()
            ->route('stores.webhooks.index')
            ->with('success', 'Webhook source deleted successfully!');
    }

    /**
     * Toggle webhook active status
     */
    public function toggle(WebhookSource $webhook)
    {
        $webhook->update([
            'is_active' => !$webhook->is_active
        ]);

        $status = $webhook->is_active ? 'enabled' : 'disabled';

        return redirect()
            ->back()
            ->with('success', "Webhook {$status} successfully!");
    }

    /**
     * Regenerate webhook token
     */
    public function regenerateToken(WebhookSource $webhook)
    {
        $webhook->update([
            'webhook_token' => Str::random(32)
        ]);

        return redirect()
            ->back()
            ->with('success', 'Webhook token regenerated successfully!')
            ->with('warning', 'Make sure to update the webhook URL in your payment provider!');
    }
}
