/**
 * Branding Routes
 * API endpoints for managing PDF branding configurations
 */

import { FastifyInstance } from 'fastify';
import { z } from 'zod';
import { brandingService } from '../services/branding.service';

const brandingSchema = z.object({
  name: z.string().min(1).optional(),
  titleFont: z.string().optional(),
  bodyFont: z.string().optional(),
  labelFont: z.string().optional(),
  primaryColor: z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional(),
  secondaryColor: z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional(),
  accentColor: z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional(),
  logoData: z.string().optional(),
});

export async function brandingRoutes(fastify: FastifyInstance) {
  // Get all branding configurations
  fastify.get('/', async (request, reply) => {
    try {
      const brandings = brandingService.listBrandings();
      reply.send({ brandings });
    } catch (error: any) {
      reply.code(500).send({ error: 'Failed to list brandings', message: error?.message });
    }
  });

  // Get a specific branding configuration
  fastify.get<{ Params: { id: string } }>('/:id', async (request, reply) => {
    try {
      const { id } = request.params;
      const branding = brandingService.getBranding(id);

      if (!branding) {
        return reply.code(404).send({ error: 'Branding not found' });
      }

      reply.send(branding);
    } catch (error: any) {
      reply.code(500).send({ error: 'Failed to get branding', message: error?.message });
    }
  });

  // Create or update branding
  fastify.post<{ Params: { id?: string } }>('/:id?', async (request, reply) => {
    try {
      const { id } = request.params;
      const body = brandingSchema.parse(request.body);

      const branding = await brandingService.saveBranding({
        ...body,
        id,
      });

      reply.send(branding);
    } catch (error: any) {
      if (error.name === 'ZodError') {
        return reply.code(400).send({ error: 'Invalid request', details: error.errors });
      }
      reply.code(500).send({ error: 'Failed to save branding', message: error?.message });
    }
  });

  // Delete branding
  fastify.delete<{ Params: { id: string } }>('/:id', async (request, reply) => {
    try {
      const { id } = request.params;

      const deleted = await brandingService.deleteBranding(id);

      if (!deleted) {
        return reply.code(404).send({ error: 'Branding not found' });
      }

      reply.send({ success: true, message: 'Branding deleted' });
    } catch (error: any) {
      reply.code(500).send({ error: 'Failed to delete branding', message: error?.message });
    }
  });

  // Get default branding
  fastify.get('/default', async (request, reply) => {
    try {
      const branding = brandingService.getDefaultBranding();
      reply.send(branding);
    } catch (error: any) {
      reply.code(500).send({ error: 'Failed to get default branding', message: error?.message });
    }
  });
}
