<?php

namespace App\Http\Controllers\Api\Payments;

use App\DTOs\Stripe\CreateCustomerDTO;
use App\DTOs\Stripe\ProductWithPriceDTO;
use App\Http\Controllers\Controller;
use App\Http\Requests\CreateProductWithPriceRequest;
use App\Http\Requests\RemovePaymentMethodRequest;
use App\Http\Requests\SetDefaultPaymentMethodRequest;
use App\Http\Requests\UpdateProductWithPricesRequest;
use App\Services\ProductStripeService;
use App\Services\StripeService;
use Illuminate\Http\Request;

class StripeController extends Controller
{
    protected StripeService $stripeService;
    protected ProductStripeService $productStripeService;

    public function __construct(StripeService $stripeService, ProductStripeService $productService)
    {
        $this->stripeService = $stripeService;
        $this->productStripeService = $productService;
    }

    public function createCustomer(Request $request)
    {
        $user = $request->user();
        $dto = new CreateCustomerDTO($user->email, $user->name, $user->id);
        return $this->stripeService->createCustomer($dto);
    }

    public function getSetupIntent(Request $request)
    {
        $user = $request->user();
        $userId = $user->id;
        return $this->stripeService->createSetupIntent($userId);
    }

    public function getCustomerPaymentMethods(string $idCustomer)
    {
        return $this->stripeService->getPaymentMethods($idCustomer);
    }

    public function removePaymentMethod(RemovePaymentMethodRequest $request)
    {
        return $this->stripeService->detachPaymentMethod($request->payment_method_id);
    }

    public function setDefaultPaymentMethod(SetDefaultPaymentMethodRequest $request)
    {
        $request->validate([
            'stripe_customer_id' => 'required|string',
            'payment_method_id' => 'required|string|regex:/^pm_[a-zA-Z0-9]+$/',
        ]);
        return $this->stripeService->setDefaultPaymentMethod(
            $request->stripe_customer_id,
            $request->payment_method_id
        );
    }

    public function getPlanSuscription(Request $request)
    {
        $includeInactive = $request->boolean('include_inactive', false);
        return $this->productStripeService->getPlans($includeInactive);
    }

    public function getPlanDetail(string $planId)
    {
        return $this->productStripeService->getPlanDetail($planId);
    }

    public function createProductWithPrice(CreateProductWithPriceRequest $request)
    {
        $dto = ProductWithPriceDTO::fromRequest($request);
        return $this->productStripeService->createProductWithPrice($dto);
    }

    public function updateProductWithPrice(UpdateProductWithPricesRequest $request, string $idPlan)
    {
        $dto = ProductWithPriceDTO::fromRequest($request);
        return $this->productStripeService->updateProductWithPrice($idPlan, $dto);
    }

    public function deletePlan(string $id)
    {
        return $this->productStripeService->deleteProductAndPlan($id);
    }
}
