import { Controller, Post, Get, HttpCode, HttpStatus, UseGuards, Query } from '@nestjs/common';
import { BackupService } from './backup.service';
import { JwtAuthGuard } from '../../modules/auth/guards/jwt-auth.guard';
import { Roles } from '../../modules/auth/decorators/roles.decorator';
import { RolesGuard } from '../../modules/auth/guards/roles.guard';

/**
 * Backup Controller
 *
 * Provides endpoints for manual backup operations
 * Restricted to admin users only
 */
@Controller('backups')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('admin') // Only admins can trigger backups
export class BackupController {
  constructor(private readonly backupService: BackupService) {}

  /**
   * Trigger manual backup
   * POST /api/v1/backups
   */
  @Post()
  @HttpCode(HttpStatus.ACCEPTED)
  async createBackup() {
    try {
      const result = await this.backupService.backupAll();
      return {
        success: true,
        message: 'Backup completed successfully',
        data: {
          postgres: result.postgres,
          mongodb: result.mongodb,
          timestamp: new Date().toISOString(),
        },
      };
    } catch (error) {
      return {
        success: false,
        message: 'Backup failed',
        error: error.message,
      };
    }
  }

  /**
   * List available backups
   * GET /api/v1/backups
   */
  @Get()
  async listBackups() {
    try {
      const backups = await this.backupService.listBackups();
      return {
        success: true,
        data: {
          backups,
          count: backups.length,
        },
      };
    } catch (error) {
      return {
        success: false,
        message: 'Failed to list backups',
        error: error.message,
      };
    }
  }

  /**
   * Restore from backup
   * POST /api/v1/backups/restore?filename=backup.sql.gz
   */
  @Post('restore')
  @HttpCode(HttpStatus.ACCEPTED)
  async restoreBackup(@Query('filename') filename: string) {
    if (!filename) {
      return {
        success: false,
        message: 'Backup filename is required',
      };
    }

    try {
      await this.backupService.restorePostgreSQL(filename);
      return {
        success: true,
        message: 'Database restored successfully',
        data: {
          filename,
          timestamp: new Date().toISOString(),
        },
      };
    } catch (error) {
      return {
        success: false,
        message: 'Restore failed',
        error: error.message,
      };
    }
  }
}
