<?php

namespace App\Services;

use App\Enums\CreditProductType;
use App\Models\CreditProduct;
use Laravel\Cashier\Cashier;

class StripeCreditProductSyncer
{
    public function sync(CreditProduct $product): CreditProduct
    {
        $stripe = Cashier::stripe();
        $stripeProductId = $product->stripe_product_id;

        if (! $stripeProductId) {
            $stripeProduct = $stripe->products->create([
                'name' => $product->name,
                'description' => $product->description,
                'metadata' => [
                    'credit_product_id' => $product->getKey(),
                    'credits' => (string) $product->credits,
                    'type' => $product->type->value,
                ],
            ]);

            $stripeProductId = $stripeProduct->id;
        }

        if (! $product->stripe_price_id) {
            $priceData = [
                'product' => $stripeProductId,
                'unit_amount' => $product->amount,
                'currency' => strtolower($product->currency),
                'metadata' => [
                    'credit_product_id' => $product->getKey(),
                    'credits' => (string) $product->credits,
                    'type' => $product->type->value,
                ],
            ];

            if ($product->type === CreditProductType::MONTHLY) {
                $priceData['recurring'] = [
                    'interval' => 'month',
                ];
            }

            $stripePrice = $stripe->prices->create($priceData);
        }

        $product->forceFill([
            'stripe_product_id' => $stripeProductId,
            'stripe_price_id' => $product->stripe_price_id ?: $stripePrice->id,
        ])->save();

        return $product;
    }
}
