<?php

namespace App\Http\Controllers\Testing;

use App\Http\Controllers\Controller;
use App\Models\CheckoutSession;
use App\Services\Checkout\CheckoutWebhookService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class TestCheckoutController extends Controller
{
    public function latest(Request $request): JsonResponse
    {
        abort_unless(config('e2e.testing_enabled'), 404);

        $validated = $request->validate([
            'email' => ['nullable', 'string', 'email'],
            'tenant_id' => ['nullable', 'integer'],
            'status' => ['nullable', 'string'],
        ]);

        $query = CheckoutSession::query()->latest();

        if ($validated['email'] ?? null) {
            $query->whereHas('user', fn ($q) => $q->where('email', $validated['email']));
        }

        if ($validated['tenant_id'] ?? null) {
            $query->where('tenant_id', $validated['tenant_id']);
        }

        if ($validated['status'] ?? null) {
            $query->where('status', $validated['status']);
        }

        $session = $query->first();

        if (! $session) {
            return response()->json([
                'data' => null,
            ], 404);
        }

        $session->loadMissing(['user', 'tenant', 'package']);

        return response()->json([
            'data' => [
                'id' => $session->id,
                'status' => $session->status,
                'provider' => $session->provider,
                'tenant_id' => $session->tenant_id,
                'package_id' => $session->package_id,
                'user_email' => $session->user?->email,
                'coupon_id' => $session->coupon_id,
                'amount_subtotal' => $session->amount_subtotal,
                'amount_total' => $session->amount_total,
                'created_at' => $session->created_at?->toIso8601String(),
            ],
        ]);
    }

    public function simulatePaddle(
        Request $request,
        CheckoutWebhookService $webhooks,
        CheckoutSession $session
    ): JsonResponse {
        abort_unless(config('e2e.testing_enabled'), 404);

        $validated = $request->validate([
            'event_type' => ['nullable', 'string'],
            'transaction_id' => ['nullable', 'string'],
            'status' => ['nullable', 'string'],
            'checkout_id' => ['nullable', 'string'],
            'metadata' => ['nullable', 'array'],
        ]);

        $eventType = $validated['event_type'] ?? 'transaction.completed';
        $metadata = array_merge([
            'tenant_id' => $session->tenant_id,
            'package_id' => $session->package_id,
            'checkout_session_id' => $session->id,
        ], $validated['metadata'] ?? []);

        $payload = [
            'event_type' => $eventType,
            'data' => array_filter([
                'id' => $validated['transaction_id'] ?? ('txn_'.Str::uuid()),
                'status' => $validated['status'] ?? 'completed',
                'custom_data' => $metadata,
                'checkout_id' => $validated['checkout_id'] ?? $session->provider_metadata['paddle_checkout_id'] ?? 'chk_'.Str::uuid(),
            ]),
        ];

        $handled = $webhooks->handlePaddleEvent($payload);

        return response()->json([
            'data' => [
                'handled' => $handled,
                'session' => [
                    'id' => $session->id,
                    'status' => $session->fresh()->status,
                ],
            ],
        ]);
    }
}
