<?php

namespace App\Services;

use App\Models\User;
use Illuminate\Http\JsonResponse;
use Stripe\Stripe;
use Illuminate\Http\Response;
use Stripe\Exception\ApiErrorException;
use Exception;
use Stripe\Customer;
use Stripe\PaymentMethod;
use Stripe\Subscription;

class SubscriptionService
{
    public function __construct()
    {
        Stripe::setApiKey(config('app.stripe.secret'));
    }

    public function createSubscription(string $stripe_customer_id, string $payment_method_id, string $price_id): JsonResponse
    {
        try {
            Customer::update($stripe_customer_id, [
                'invoice_settings' => [
                    'default_payment_method' => $payment_method_id,
                ],
            ]);
            // Crear la suscripción
            $subscription = Subscription::create([
                'customer' => $stripe_customer_id,
                'items' => [[
                    'price' => $price_id,
                ]],
                'default_payment_method' => $payment_method_id,
                'expand' => ['latest_invoice.payment_intent'],
            ]);

            return response()->json([
                'message' => 'Suscripción creada exitosamente.',
                'subscription_id' => $subscription->id,
            ], Response::HTTP_OK);
        } catch (\Stripe\Exception\ApiErrorException $e) {
            return response()->json(['error' => 'Error con Stripe: ' . $e->getMessage()], 500);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Error inesperado: ' . $e->getMessage()], 500);
        }
    }

    public function updateCustomerSubscription(string $subscription_id, string $new_price_id): JsonResponse
    {
        try {
            // Obtener la suscripción actual del cliente
            $subscription = \Stripe\Subscription::retrieve($subscription_id);

            // Verificar que la suscripción tenga al menos un ítem
            if (empty($subscription->items->data)) {
                return response()->json([
                    'error' => 'La suscripción no tiene elementos para actualizar.'
                ], 400);
            }

            $current_item_id = $subscription->items->data[0]->id;

            // Actualizar el plan/precio de la suscripción del cliente
            $updated = \Stripe\Subscription::update($subscription_id, [
                'cancel_at_period_end' => false, // Cambio inmediato, no al final del periodo
                'items' => [[
                    'id' => $current_item_id,
                    'price' => $new_price_id,
                ]],
            ]);

            return response()->json([
                'message' => 'Tu suscripción ha sido actualizada exitosamente.',
                'subscription_id' => $updated->id,
                'current_plan' => $new_price_id
            ], Response::HTTP_OK);
        } catch (\Stripe\Exception\ApiErrorException $e) {
            return response()->json([
                'error' => 'Ocurrió un error al actualizar tu suscripción: ' . $e->getMessage()
            ], 500);
        } catch (\Exception $e) {
            return response()->json([
                'error' => 'Error inesperado: ' . $e->getMessage()
            ], 500);
        }
    }

    public function cancelSubscription(string $subscription_id): JsonResponse
    {
        try {
            $subscription = \Stripe\Subscription::retrieve($subscription_id);
            $subscription->cancel();
            return response()->json([
                'message' => 'Suscripción cancelada correctamente.',
            ], Response::HTTP_OK);
        } catch (\Stripe\Exception\ApiErrorException $e) {
            return response()->json(['error' => 'Error con Stripe: ' . $e->getMessage()], 500);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Error inesperado: ' . $e->getMessage()], 500);
        }
    }
}
