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

interface PortalRequest {
  organizationId: string
}

interface PortalResponse {
  url: string
}

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody<PortalRequest>(event)

    if (!body.organizationId) {
      throw ApiErrors.validationError('Organization ID is required')
    }

    await validateOrganizationAccess(event, body.organizationId)

    const customer = await getCustomerByUserId(body.organizationId)
    if (!customer) {
      throw ApiErrors.notFound('Customer not found')
    }

    const session = await stripeService.createBillingPortalSession(customer.id)
    return createSuccessResponse<PortalResponse>({ url: session.url || '' }, 'Billing portal session created')
  } catch (error) {
    throw handleApiError(error)
  }
})
