/**
 * @ai-summary User export controller
 * @ai-context Handles HTTP requests for user data export
 */

import { FastifyRequest, FastifyReply } from 'fastify';
import { UserExportService } from '../domain/user-export.service';
import { logger } from '../../../core/logging/logger';

export class UserExportController {
  private exportService: UserExportService;

  constructor() {
    this.exportService = new UserExportService();
  }

  async downloadExport(request: FastifyRequest, reply: FastifyReply): Promise<void> {
    const userId = (request as any).user.sub;

    logger.info('User export requested', { userId });

    try {
      const result = await this.exportService.exportUserData(userId);

      logger.info('User export ready for download', {
        userId,
        filename: result.filename,
        sizeBytes: result.size,
      });

      return reply
        .header('Content-Type', 'application/gzip')
        .header('Content-Disposition', `attachment; filename="${result.filename}"`)
        .header('Content-Length', result.size)
        .send(result.stream);
    } catch (error) {
      logger.error('User export failed', {
        userId,
        error: error instanceof Error ? error.message : String(error),
      });
      throw error;
    }
  }
}
