import type { FastifyInstance } from 'fastify';
import { createBackup, getBackups, getBackup, restoreBackup, deleteBackup } from './repository.js';
import { BackupParamsSchema, RestoreParamsSchema } from './types.js';
import { requireAdmin } from '../../lib/auth.js';

export async function backupRoutes(fastify: FastifyInstance) {
  // Create backup (admin only)
  fastify.post('/backups', {
    preHandler: async (req) => requireAdmin(req),
  }, async (req, reply) => {
    try {
      const params = BackupParamsSchema.parse(req.body);
      const backup = await createBackup(params);
      return reply.code(201).send(backup);
    } catch (error) {
      fastify.log.error(error, 'Backup creation failed');
      return reply.code(500).send({ error: 'Failed to create backup' });
    }
  });

  // List backups (admin only)
  fastify.get('/backups', {
    preHandler: async (req) => requireAdmin(req),
  }, async (req, reply) => {
    try {
      const backups = await getBackups();
      return reply.send(backups);
    } catch (error) {
      fastify.log.error(error, 'Failed to get backups');
      return reply.code(500).send({ error: 'Failed to get backups' });
    }
  });

  // Get single backup (admin only)
  fastify.get('/backups/:id', {
    preHandler: async (req) => requireAdmin(req),
  }, async (req, reply) => {
    try {
      const { id } = req.params as { id: string };
      const backup = await getBackup(id);
      if (!backup) {
        return reply.code(404).send({ error: 'Backup not found' });
      }
      return reply.send(backup);
    } catch (error) {
      fastify.log.error(error, 'Failed to get backup');
      return reply.code(500).send({ error: 'Failed to get backup' });
    }
  });

  // Restore backup (admin only)
  fastify.post('/backups/:id/restore', {
    preHandler: async (req) => requireAdmin(req),
  }, async (req, reply) => {
    try {
      const { id } = req.params as { id: string };
      await restoreBackup(id);
      return reply.send({ message: 'Backup restored successfully' });
    } catch (error: any) {
      fastify.log.error(error, 'Restore failed');
      return reply.code(500).send({ error: error.message || 'Failed to restore backup' });
    }
  });

  // Delete backup (admin only)
  fastify.delete('/backups/:id', {
    preHandler: async (req) => requireAdmin(req),
  }, async (req, reply) => {
    try {
      const { id } = req.params as { id: string };
      await deleteBackup(id);
      return reply.code(204).send();
    } catch (error) {
      fastify.log.error(error, 'Failed to delete backup');
      return reply.code(500).send({ error: 'Failed to delete backup' });
    }
  });
}
