import type { Database } from '@pig/db';
import { Hono } from 'hono';
import { z } from 'zod';
import type { ApiEnv } from '../lib/mutation';
import { apiError } from '../lib/mutation';
import { CustomerLifecycleService } from '../services/customer-lifecycle';

const accountIdSchema = z.string().uuid();

/*
 * These used to carry their own `requireGrowthRead`, which asked whether the
 * *credential* had the 'read' scope. That was the right instinct and the wrong
 * question: scope is a property of the API key, and it said nothing about
 * whether the person holding it may see the growth book. Both halves are now
 * asked once, for every read in the product, by the READ_RULES table —
 * `requireReadCapability` checks the scope first and then `book:read`.
 */
export function createGrowthRoutes(db: Database): Hono<ApiEnv> {
  const routes = new Hono<ApiEnv>();
  const service = new CustomerLifecycleService(db);

  routes.get('/api/growth', async (context) => context.json(await service.report()));
  routes.get('/api/growth/accounts/:id', async (context) => {
    const accountId = accountIdSchema.safeParse(context.req.param('id'));
    if (!accountId.success) {
      return context.json(apiError('invalid_account', 'Invalid account ID.', accountId.error.issues), 400);
    }
    const customer = await service.account(accountId.data);
    return customer
      ? context.json(customer)
      : context.json(apiError('not_found', 'Growth account not found.'), 404);
  });
  return routes;
}
