<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Api\V1\Concerns\RespondsWithApi;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class WebhookController extends Controller
{
    use RespondsWithApi;

    public function payment(Request $request, string $gateway)
    {
        $payload = $request->all();
        $eventType = $payload['event'] ?? $payload['type'] ?? 'payment.webhook';
        $gatewayEventId = $payload['id'] ?? $payload['event_id'] ?? null;

        DB::table('payment_webhooks')->insert([
            'gateway' => $gateway,
            'event_type' => $eventType,
            'gateway_event_id' => $gatewayEventId,
            'payload_json' => json_encode($payload),
            'signature_valid' => $this->signatureLooksValid($request),
            'processed_at' => now(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return $this->ok(['received' => true], 'Webhook stored.');
    }

    public function communications(Request $request)
    {
        DB::table('communication_logs')->insert([
            'channel' => $request->input('channel', 'unknown'),
            'recipient' => $request->input('recipient', 'unknown'),
            'payload_json' => json_encode($request->all()),
            'provider' => $request->input('provider', 'webhook'),
            'provider_reference' => $request->input('id'),
            'status' => $request->input('status', 'received'),
            'sent_at' => now(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return $this->ok(['received' => true], 'Communication webhook stored.');
    }

    private function signatureLooksValid(Request $request): bool
    {
        if (! env('WEBHOOK_SECRET')) {
            return false;
        }

        return (bool) $request->header('X-Webhook-Signature');
    }
}
