import { Injectable, Logger } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import Stripe from 'stripe'

// Thin wrapper around the Stripe SDK. Dark-launch friendly: the SDK is only
// constructed lazily on first use, so the app boots fine in dev with no Stripe
// keys. `enabled` gates the live money-moving paths (subscription create on
// tenant create, webhook processing). When disabled, billing reads run on
// DERIVED data (Subscription + Price + marginPct) instead of live Stripe.
@Injectable()
export class StripeClient {
  private readonly logger = new Logger(StripeClient.name)
  private readonly secretKey?: string
  private readonly webhookSecret?: string
  // Publishable key is safe to hand to the browser — it's how the portal mounts
  // Stripe Elements. Exposed via getter so the billing endpoints can return it.
  readonly publishableKey?: string
  private _stripe?: Stripe
  readonly enabled: boolean

  constructor(config: ConfigService) {
    this.secretKey = config.get<string>('STRIPE_SECRET_KEY')
    this.publishableKey = config.get<string>('STRIPE_PUBLISHABLE_KEY')
    this.webhookSecret = config.get<string>('STRIPE_WEBHOOK_SECRET')
    this.enabled = config.get<string>('BILLING_STRIPE_ENABLED') === 'true' && !!this.secretKey
    if (!this.enabled) {
      this.logger.log(
        'Stripe billing disabled (BILLING_STRIPE_ENABLED != true or no key) — billing uses derived data.',
      )
    }
  }

  get hasWebhookSecret(): boolean {
    return !!this.webhookSecret
  }

  // Lazy SDK accessor — throws only if actually used while unconfigured.
  private get stripe(): Stripe {
    if (!this.secretKey) {
      throw new Error('Stripe is not configured (STRIPE_SECRET_KEY missing)')
    }
    if (!this._stripe) this._stripe = new Stripe(this.secretKey)
    return this._stripe
  }

  async createCustomer(input: {
    name: string
    email?: string
    metadata?: Record<string, string>
  }): Promise<string> {
    const c = await this.stripe.customers.create({
      name: input.name,
      email: input.email,
      metadata: input.metadata,
    })
    return c.id
  }

  // Create (or reuse) a recurring Stripe Price for a catalog row. We pass
  // product_data so Stripe creates the backing Product in the same call; the
  // resulting price id is persisted on the Price doc (stripePriceIds[currency])
  // so we only hit Stripe once per (plan, cycle, currency).
  async createPrice(input: {
    productName: string
    currency: string // ISO, lower-cased by Stripe
    unitAmountMinor: number
    interval: 'month' | 'year'
    intervalCount: number
    metadata?: Record<string, string>
  }): Promise<string> {
    const price = await this.stripe.prices.create({
      currency: input.currency.toLowerCase(),
      unit_amount: input.unitAmountMinor,
      recurring: { interval: input.interval, interval_count: input.intervalCount },
      product_data: { name: input.productName },
      metadata: input.metadata,
    })
    return price.id
  }

  async createSubscription(input: {
    customerId: string
    priceId: string
    quantity: number
  }): Promise<{ id: string; currentPeriodEnd?: number; status: string }> {
    // send_invoice (not charge_automatically) so a test subscription produces
    // a real open invoice without a saved payment method — that's what the
    // billing pages and the webhook flow consume in dev/test.
    const s = await this.stripe.subscriptions.create({
      customer: input.customerId,
      items: [{ price: input.priceId, quantity: input.quantity }],
      collection_method: 'send_invoice',
      days_until_due: 14,
    })
    return {
      id: s.id,
      currentPeriodEnd: (s as { current_period_end?: number }).current_period_end,
      status: s.status,
    }
  }

  // Suspend billing without losing the subscription — collection is voided
  // while paused, then resumed on unpause. Mirrors tenant suspend/resume.
  async pauseSubscription(subscriptionId: string): Promise<void> {
    await this.stripe.subscriptions.update(subscriptionId, {
      pause_collection: { behavior: 'void' },
    })
  }

  async resumeSubscription(subscriptionId: string): Promise<void> {
    await this.stripe.subscriptions.update(subscriptionId, { pause_collection: null })
  }

  async updateSubscriptionQuantity(subscriptionId: string, quantity: number): Promise<void> {
    const sub = await this.stripe.subscriptions.retrieve(subscriptionId)
    const itemId = sub.items.data[0]?.id
    if (!itemId) throw new Error(`Stripe subscription ${subscriptionId} has no line items`)
    await this.stripe.subscriptions.update(subscriptionId, { items: [{ id: itemId, quantity }] })
  }

  // Repoint a subscription's line item at a different Price. Stripe Prices are
  // immutable, so a catalog "price change" means minting a new Price and moving
  // live subscriptions onto it. proration_behavior 'none' → no mid-cycle charge
  // or credit; the new amount takes effect at the next renewal. Quantity is
  // preserved (we only swap the price).
  async updateSubscriptionPrice(subscriptionId: string, priceId: string): Promise<void> {
    const sub = await this.stripe.subscriptions.retrieve(subscriptionId)
    const itemId = sub.items.data[0]?.id
    if (!itemId) throw new Error(`Stripe subscription ${subscriptionId} has no line items`)
    await this.stripe.subscriptions.update(subscriptionId, {
      items: [{ id: itemId, price: priceId }],
      proration_behavior: 'none',
    })
  }

  async cancelSubscription(subscriptionId: string): Promise<void> {
    await this.stripe.subscriptions.cancel(subscriptionId)
  }

  async listInvoices(customerId: string, limit = 50): Promise<Stripe.Invoice[]> {
    const res = await this.stripe.invoices.list({ customer: customerId, limit })
    return res.data
  }

  // ── Payment methods (customer-admin "card on file" flow) ──────────────────

  // The customer's default card, if any. Prefers the invoice-settings default;
  // falls back to the first attached card. Returns null when none is on file.
  async getDefaultCard(customerId: string): Promise<{
    brand: string
    last4: string
    expMonth: number
    expYear: number
  } | null> {
    const customer = await this.stripe.customers.retrieve(customerId, {
      expand: ['invoice_settings.default_payment_method'],
    })
    if (customer.deleted) return null

    let pm = customer.invoice_settings?.default_payment_method as Stripe.PaymentMethod | null
    if (!pm || typeof pm === 'string') {
      const list = await this.stripe.paymentMethods.list({ customer: customerId, type: 'card', limit: 1 })
      pm = list.data[0] ?? null
    }
    if (!pm?.card) return null
    return {
      brand: pm.card.brand,
      last4: pm.card.last4,
      expMonth: pm.card.exp_month,
      expYear: pm.card.exp_year,
    }
  }

  // SetupIntent to collect a card off-session for future invoices. The portal
  // confirms it client-side with Stripe Elements using the returned secret.
  async createSetupIntent(customerId: string): Promise<string> {
    const si = await this.stripe.setupIntents.create({
      customer: customerId,
      payment_method_types: ['card'],
      usage: 'off_session',
    })
    if (!si.client_secret) throw new Error('SetupIntent has no client_secret')
    return si.client_secret
  }

  // After a SetupIntent succeeds, make the new card the customer's default for
  // invoices (and for the active subscription, if any). The PM is already
  // attached to the customer by the SetupIntent.
  async setDefaultCard(customerId: string, paymentMethodId: string, subscriptionId?: string): Promise<void> {
    await this.stripe.customers.update(customerId, {
      invoice_settings: { default_payment_method: paymentMethodId },
    })
    if (subscriptionId) {
      await this.stripe.subscriptions.update(subscriptionId, { default_payment_method: paymentMethodId })
    }
  }

  constructWebhookEvent(rawBody: Buffer | string, signature: string): Stripe.Event {
    if (!this.webhookSecret) throw new Error('Stripe webhook secret not configured')
    return this.stripe.webhooks.constructEvent(rawBody, signature, this.webhookSecret)
  }
}
