import { FastifyInstance } from 'fastify';
import { prisma } from '../../config/database.js';
import { authMiddleware } from '../middleware/auth.middleware.js';
import { updateTenantSchema } from '../middleware/validate.js';
import { generateWebhookSecret } from '../../utils/crypto.js';
import { successResponse, errorResponse } from '../../utils/helpers.js';

export async function tenantRoutes(app: FastifyInstance) {
  // All routes require auth
  app.addHook('preHandler', authMiddleware);

  // PUT /api/v1/tenant
  app.put('/', async (request, reply) => {
    const parsed = updateTenantSchema.safeParse(request.body);
    if (!parsed.success) {
      return errorResponse(reply, 'Validation error', 400, parsed.error.flatten());
    }

    const tenant = await prisma.tenant.update({
      where: { id: request.tenantId! },
      data: parsed.data as any,
      select: {
        id: true,
        name: true,
        slug: true,
        email: true,
        domain: true,
        webhookUrl: true,
        settings: true,
        updatedAt: true,
      },
    });

    return successResponse(reply, tenant);
  });

  // POST /api/v1/tenant/webhook-secret/regenerate
  app.post('/webhook-secret/regenerate', async (request, reply) => {
    const webhookSecret = generateWebhookSecret();

    await prisma.tenant.update({
      where: { id: request.tenantId! },
      data: { webhookSecret },
    });

    return successResponse(reply, { webhookSecret });
  });

  // GET /api/v1/tenant/stats
  app.get('/stats', async (request, reply) => {
    const tenantId = request.tenantId!;

    const [productCount, sessionCount, totalBids, totalCartEvents] = await Promise.all([
      prisma.product.count({ where: { tenantId } }),
      prisma.liveSession.count({ where: { tenantId } }),
      prisma.bid.count({
        where: { auctionItem: { liveSession: { tenantId } } },
      }),
      prisma.cartEvent.count({ where: { tenantId } }),
    ]);

    return successResponse(reply, {
      products: productCount,
      sessions: sessionCount,
      totalBids,
      totalCartEvents,
    });
  });
}
