module Billing
  module Stripe
    class CheckoutSession
      VALID_PLANS = %w[premium_light premium_full].freeze

      def initialize(team:, user:, plan_slug: "premium_light")
        @team = team
        @user = user
        @plan_slug = plan_slug.to_s
      end

      def url
        raise "Stripe non configurato" unless MatchLiveTv.stripe_enabled?
        raise "Piano non valido" unless VALID_PLANS.include?(@plan_slug)

        plan = Plan[@plan_slug]
        price_id = plan.stripe_price_id.presence || stripe_price_id_for(@plan_slug)
        raise "Price ID Stripe mancante per #{@plan_slug}" if price_id.blank?

        customer_id = ensure_customer_id!
        session = ::Stripe::Checkout::Session.create(
          mode: "subscription",
          customer: customer_id,
          line_items: [{ price: price_id, quantity: 1 }],
          success_url: success_url,
          cancel_url: cancel_url,
          metadata: { team_id: @team.id, user_id: @user.id, plan_slug: @plan_slug },
          subscription_data: { metadata: { team_id: @team.id, plan_slug: @plan_slug } }
        )
        session.url
      end

      def portal_url
        raise "Stripe non configurato" unless MatchLiveTv.stripe_enabled?

        customer_id = ensure_customer_id!
        session = ::Stripe::BillingPortal::Session.create(
          customer: customer_id,
          return_url: dashboard_url
        )
        session.url
      end

      private

      def stripe_price_id_for(slug)
        case slug
        when "premium_light" then MatchLiveTv.stripe_premium_light_price_id
        when "premium_full" then MatchLiveTv.stripe_premium_full_price_id
        end
      end

      def ensure_customer_id!
        sub = @team.subscription || @team.build_subscription(plan: Plan["free"], status: "active")
        return sub.stripe_customer_id if sub.stripe_customer_id.present?

        customer = ::Stripe::Customer.create(
          email: @user.email,
          name: @team.name,
          metadata: { team_id: @team.id }
        )
        sub.update!(stripe_customer_id: customer.id)
        customer.id
      end

      def success_url
        "#{dashboard_url}?checkout=success"
      end

      def cancel_url
        "#{dashboard_url}?checkout=canceled"
      end

      def dashboard_url
        "#{MatchLiveTv.app_public_url.chomp('/')}/teams/#{@team.id}/dashboard"
      end
    end
  end
end
