import { deleteStripeProduct } from '../../../database/queries/stripe'
import { useDB, eq } from '../../../utils/database'
import { prices } from '../../../database/schema'
import { requireSuperAdmin } from '../../../utils/auth'
import { handleApiError, ApiErrors, createSuccessResponse } from '../../../utils/errors'

interface DeleteProductResponse {
  productId: string
  deleted: boolean
}

export default defineEventHandler(async (event) => {
  try {
    await requireSuperAdmin(event)

    const productId = getRouterParam(event, 'id')
    if (!productId) {
      throw ApiErrors.validationError('Product ID is required')
    }

    const db = useDB()
    await db.delete(prices).where(eq(prices.productId, productId))
    await deleteStripeProduct(productId)

    return createSuccessResponse<DeleteProductResponse>({
      productId,
      deleted: true
    }, 'Product deleted successfully')
  } catch (error) {
    throw handleApiError(error)
  }
})
