/**
 * Authenticated marketplace entitlement routes (subscribe, workspace entitlements).
 */
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'
import { requireTenant } from '../middleware/tenant-auth.js'
import { marketplaceSubscriptionService } from '../services/marketplace-subscription.js'
import { operatingModelService } from '../services/operating-model.js'

function tenantFromRequest(request: FastifyRequest, reply: FastifyReply) {
  const headerTenant = (request.headers['x-tenant-id'] as string | undefined)?.trim()
  if (headerTenant && request.tenantContext) {
    request.tenantContext = { ...request.tenantContext, tenantId: headerTenant }
  }
  return requireTenant(request, reply)
}

export async function registerMarketplaceEntitlementRoutes(fastify: FastifyInstance) {
  fastify.post('/api/v1/marketplace/subscribe', async (request, reply) => {
    const tenantContext = tenantFromRequest(request, reply)
    const body = (request.body || {}) as { productSlug?: string; sku?: string; syncKeycloak?: boolean }
    if (!body.productSlug?.trim()) {
      return reply.code(400).send({ error: 'productSlug is required' })
    }

    try {
      const result = await marketplaceSubscriptionService.subscribeToProduct(
        { request, user: (request as any).user, tenantContext, db: undefined as any },
        {
          productSlug: body.productSlug.trim(),
          sku: body.sku?.trim(),
          syncKeycloak: body.syncKeycloak,
        }
      )
      return reply.send(result)
    } catch (error: any) {
      const message = error?.message || 'Subscribe failed'
      const code = message.includes('Tenant') ? 403 : message.includes('not found') ? 404 : 400
      return reply.code(code).send({ error: message })
    }
  })

  fastify.get('/api/v1/marketplace/me/entitlements', async (request, reply) => {
    const tenantContext = tenantFromRequest(request, reply)
    const entitlements = await marketplaceSubscriptionService.getTenantEntitlements(
      tenantContext.tenantId!
    )
    const subscriptions = await marketplaceSubscriptionService.getTenantSubscriptions(
      tenantContext.tenantId!
    )
    const client = await operatingModelService.getClientByTenantId(tenantContext.tenantId!)
    return reply.send({ client, subscriptions, entitlements })
  })
}
