<?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;
        } else {
            $stripe->products->update($stripeProductId, [
                'name' => $product->name,
                'description' => $product->description,
                'active' => (bool) $product->is_active,
                'metadata' => [
                    'credit_product_id' => $product->getKey(),
                    'credits' => (string) $product->credits,
                    'type' => $product->type->value,
                ],
            ]);
        }

        $needsNewPrice = false;

        if (! $product->stripe_price_id) {
            $needsNewPrice = true;
        } elseif ($product->wasChanged(['amount', 'currency', 'type', 'credits'])) {
            $needsNewPrice = true;
        }

        $stripePriceId = $product->stripe_price_id;

        if ($needsNewPrice) {
            $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);
            $stripePriceId = $stripePrice->id;

            // Archive the old price if it exists
            if ($product->stripe_price_id && $product->stripe_price_id !== $stripePriceId) {
                try {
                    $stripe->prices->update($product->stripe_price_id, [
                        'active' => false,
                    ]);
                } catch (\Exception $e) {
                    // Ignore error if price not found
                }
            }
        }

        if ($product->stripe_product_id !== $stripeProductId || $product->stripe_price_id !== $stripePriceId) {
            $product->forceFill([
                'stripe_product_id' => $stripeProductId,
                'stripe_price_id' => $stripePriceId,
            ])->saveQuietly();
        }

        return $product;
    }
}
