<?php

namespace App\Http\Controllers;

use App\Models\Package;
use App\Support\ApiError;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Stripe\PaymentIntent;
use Stripe\Stripe;
use Symfony\Component\HttpFoundation\Response;

class StripePaymentController extends Controller
{
    public function __construct()
    {
        Stripe::setApiKey(config('services.stripe.secret'));
    }

    public function createPaymentIntent(Request $request): JsonResponse
    {
        $request->validate([
            'package_id' => 'required|integer|exists:packages,id',
        ]);

        $user = Auth::user();
        if (! $user) {
            return ApiError::response(
                'unauthenticated',
                'Nicht authentifiziert',
                'Bitte melde dich an, um einen Kauf zu starten.',
                Response::HTTP_UNAUTHORIZED
            );
        }

        $tenant = $user->tenant;
        if (! $tenant) {
            return ApiError::response(
                'tenant_not_found',
                'Tenant nicht gefunden',
                'Für dein Benutzerkonto konnte kein Tenant gefunden werden.',
                Response::HTTP_FORBIDDEN
            );
        }

        $package = Package::findOrFail($request->package_id);

        // Kostenlose Pakete brauchen kein Payment Intent
        if ($package->price <= 0) {
            return response()->json([
                'type' => 'free',
                'message' => 'Kostenloses Paket - kein Payment Intent nötig',
            ]);
        }

        try {
            $paymentIntent = PaymentIntent::create([
                'amount' => (int) ($package->price * 100), // In Cent
                'currency' => 'eur',
                'metadata' => [
                    'package_id' => $package->id,
                    'tenant_id' => $tenant->id,
                    'user_id' => $user->id,
                    'type' => $package->type === 'endcustomer' ? 'endcustomer_event' : 'reseller_subscription',
                ],
                'automatic_payment_methods' => [
                    'enabled' => true,
                ],
                'description' => "Paket: {$package->name}",
                'receipt_email' => $user->email,
            ]);

            Log::info('Payment Intent erstellt', [
                'payment_intent_id' => $paymentIntent->id,
                'package_id' => $package->id,
                'tenant_id' => $tenant->id,
                'amount' => $package->price,
            ]);

            return response()->json([
                'clientSecret' => $paymentIntent->client_secret,
                'paymentIntentId' => $paymentIntent->id,
            ]);
        } catch (\Exception $e) {
            Log::error('Stripe Payment Intent Fehler', [
                'error' => $e->getMessage(),
                'package_id' => $request->package_id,
                'user_id' => $user->id,
            ]);

            return ApiError::response(
                'stripe_payment_error',
                'Stripe Fehler',
                'Die Zahlung konnte nicht vorbereitet werden.',
                Response::HTTP_BAD_REQUEST,
                ['stripe_message' => $e->getMessage()]
            );
        }
    }
}
