import type { FastifyInstance } from 'fastify';
import type { GitBackupService } from '../services/backup/git-backup.service.js';

export function registerGitBackupRoutes(app: FastifyInstance, gitBackup: GitBackupService): void {
  // GET /api/v1/backup/status — sync status (includes publicKey)
  app.get('/api/v1/backup/status', async () => {
    return gitBackup.getStatus();
  });

  // GET /api/v1/backup/log — commit history
  app.get<{ Querystring: { limit?: string } }>('/api/v1/backup/log', async (request) => {
    const limit = parseInt(request.query.limit ?? '50', 10);
    const entries = await gitBackup.getLog(limit);
    return { entries };
  });

  // POST /api/v1/backup/restore/preview — preview restore
  app.post<{ Body: { commit: string } }>('/api/v1/backup/restore/preview', async (request, reply) => {
    if (!gitBackup.enabled) {
      return reply.code(503).send({ error: 'Backup is not configured' });
    }
    const { commit } = request.body ?? {};
    if (!commit) {
      return reply.code(400).send({ error: 'commit is required' });
    }
    try {
      const preview = await gitBackup.previewRestore(commit);
      return preview;
    } catch (err) {
      return reply.code(400).send({ error: `Invalid commit: ${err}` });
    }
  });

  // POST /api/v1/backup/restore — restore to a commit
  app.post<{ Body: { commit: string } }>('/api/v1/backup/restore', async (request, reply) => {
    if (!gitBackup.enabled) {
      return reply.code(503).send({ error: 'Backup is not configured' });
    }
    const { commit } = request.body ?? {};
    if (!commit) {
      return reply.code(400).send({ error: 'commit is required' });
    }
    try {
      const result = await gitBackup.restoreTo(commit);
      return result;
    } catch (err) {
      return reply.code(500).send({ error: `Restore failed: ${err}` });
    }
  });
}
