import type { FastifyInstance } from 'fastify';
import { extractAuth } from '../../lib/auth.js';
import { BadRequestError } from '../../lib/errors.js';
import { SendEmailSchema, SendTestEmailSchema } from './types.js';
import { BUILT_IN_TEMPLATES } from './templates.js';
import { dispatchEmail } from './dispatcher.js';
import * as repo from './repository.js';

const DEFAULT_PRODUCT_ID = 'lysnrai';

export async function deliveryRoutes(app: FastifyInstance) {
  // List all email templates
  app.get('/delivery/templates', async req => {
    await extractAuth(req);
    return BUILT_IN_TEMPLATES.map(({ id, name, subject, variables }) => ({
      id,
      name,
      subject,
      variables,
    }));
  });

  // Get a specific template (full content)
  app.get('/delivery/templates/:id', async req => {
    await extractAuth(req);
    const { id } = req.params as { id: string };
    const template = BUILT_IN_TEMPLATES.find(t => t.id === id);
    if (!template) throw new BadRequestError(`Template '${id}' not found`);
    return template;
  });

  // Send an email via template
  app.post('/delivery/send-email', async req => {
    await extractAuth(req);
    const parsed = SendEmailSchema.safeParse(req.body);
    if (!parsed.success) {
      throw new BadRequestError(parsed.error.issues.map(i => i.message).join('; '));
    }

    const result = await dispatchEmail(
      {
        to: parsed.data.to,
        templateId: parsed.data.templateId,
        variables: parsed.data.variables,
        productId: parsed.data.productId,
      },
      req.log
    );

    if (!result.success) {
      throw new BadRequestError(`Email delivery failed: ${result.error}`);
    }

    return { success: true, messageId: result.messageId };
  });

  // Send a test email (admin only, uses default productId)
  app.post('/delivery/send-test', async req => {
    await extractAuth(req);
    const parsed = SendTestEmailSchema.safeParse(req.body);
    if (!parsed.success) {
      throw new BadRequestError(parsed.error.issues.map(i => i.message).join('; '));
    }

    const result = await dispatchEmail(
      {
        to: parsed.data.to,
        templateId: parsed.data.templateId,
        variables: parsed.data.variables,
        productId: DEFAULT_PRODUCT_ID,
      },
      req.log
    );

    return { success: result.success, messageId: result.messageId, error: result.error };
  });

  // List delivery logs
  app.get('/delivery/logs', async req => {
    await extractAuth(req);
    const query = req.query as Record<string, string>;
    return repo.listDeliveryLogs(DEFAULT_PRODUCT_ID, {
      channel: query.channel,
      status: query.status,
      limit: query.limit ? parseInt(query.limit, 10) : undefined,
    });
  });

  // Get delivery stats
  app.get('/delivery/stats', async req => {
    await extractAuth(req);
    return repo.getDeliveryStats(DEFAULT_PRODUCT_ID);
  });
}
