import Stripe from 'stripe'
import {
  createOrUpdateStripeProduct,
  createOrUpdateStripePrice
} from '../database/queries/stripe'

export default defineTask({
  meta: {
    name: 'sync-stripe-data',
    description: 'Sync Stripe products and prices with local database'
  },
  async run() {
    const config = useRuntimeConfig()
    if (!config.stripeSecretKey) {
      throw createError({ statusCode: 500, statusMessage: 'Stripe secret key not configured' })
    }
    const stripe = new Stripe(config.stripeSecretKey, { apiVersion: '2025-11-17.clover' })
    console.log('Syncing Stripe products and prices...')
    try {
      // Sync Products
      const products = await stripe.products.list({ active: true })
      console.log(`Found ${products.data.length} active products`)
      for (const product of products.data) {
        await createOrUpdateStripeProduct({
          id: product.id,
          name: product.name,
          description: product.description,
          active: product.active,
          metadata: (product.metadata as unknown) as Record<string, unknown> | null,
          features: (product as Stripe.Product & { marketing_features?: Array<{ name?: string }> })
            .marketing_features
            ? (product as Stripe.Product & { marketing_features?: Array<{ name?: string }> })
                .marketing_features!
                .filter(f => !!f?.name)
                .map(f => ({ name: f!.name as string }))
            : null
        })
      }

      // Sync Prices
      console.log('💰 Fetching prices...')
      const prices = await stripe.prices.list({ active: true })
      console.log(`Found ${prices.data.length} active prices`)
      for (const price of prices.data) {
        await createOrUpdateStripePrice({
          id: price.id,
          type: price.type,
          currency: price.currency,
          unitAmount: price.unit_amount ?? 0,
          interval: price.recurring?.interval ?? 'month',
          intervalCount: price.recurring?.interval_count ?? 1,
          productId:
            typeof price.product === 'string'
              ? price.product
              : price.product.id,
          description: price.nickname,
          active: price.active,
          metadata: (price.metadata as unknown) as Record<string, unknown> | null,
          trialPeriodDays: price.recurring?.trial_period_days
        })
      }

      return {
        result: { success: true, message: 'Stripe data synced successfully' }
      }
    } catch (error) {
      console.error('Error syncing products:', error)
      throw createError({
        statusCode: 500,
        statusMessage: 'Error syncing products'
      })
    }
  }
})
