import { stripeService } from '../../services/stripe.ts'
import { validateOrganizationOwnership } from '../../utils/organizationValidation.ts'
import {
  getCustomerByUserId,
  createCustomer
} from '../../database/queries/customers.ts'
import { requireUserSession } from '../../utils/auth.ts'
import { handleApiError, ApiErrors, createSuccessResponse } from '../../utils/errors'

interface CheckoutBody {
  priceId: string
  organizationId: string
}

interface CheckoutResponse {
  url: string
}

async function getOrCreateCustomer(
  organizationId: string,
  user: { id: string, email: string }
) {
  try {
    const customerRecord = await getCustomerByUserId(organizationId)
    if (customerRecord) {
      return customerRecord.id
    }

    const newCustomerId = await stripeService.createCustomer(organizationId, user.email)

    await createCustomer({
      id: newCustomerId,
      userId: organizationId
    })
    return newCustomerId
  } catch (error) {
    console.error('[Checkout] Error in getOrCreateCustomer:', error)
    throw ApiErrors.internalError('Failed to get or create customer')
  }
}

export default defineEventHandler(async (event) => {
  try {
    const session = await requireUserSession(event)

    const body = await readBody<CheckoutBody>(event)

    if (!body.priceId || !body.organizationId) {
      throw ApiErrors.validationError('Price ID and organization ID are required')
    }

    await validateOrganizationOwnership(event, body.organizationId)

    const customerId = await getOrCreateCustomer(body.organizationId, session.user)

    const checkoutSession = await stripeService.createCheckoutSession({
      customerId,
      priceId: body.priceId,
      organizationId: body.organizationId
    })

    return createSuccessResponse<CheckoutResponse>({
      url: checkoutSession.url || ''
    }, 'Checkout session created')
  } catch (error) {
    throw handleApiError(error)
  }
})
