import {
  Controller,
  Post,
  UseGuards,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import { MigrationGuard } from './migration.guard';
import { MigrationService } from './migration.service';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
} from '@nestjs/swagger';

/**
 * MigrationController - Controller for database migration operations
 *
 * This controller provides HTTP endpoints for executing database migrations
 * in a controlled manner. It's protected by MigrationGuard to ensure only
 * authorized users (typically administrators or CI/CD systems) can trigger
 * migrations.
 *
 * Security considerations:
 * - Migration endpoints should be disabled in production or heavily restricted
 * - Use strong authentication/authorization (MigrationGuard)
 * - Consider IP whitelisting for migration endpoints
 * - Log all migration attempts for audit purposes
 *
 * @example
 * // Run migrations (requires proper authorization)
 * POST /migration/up
 *
 * @example
 * // Rollback migrations (commented out for safety)
 * // POST /migration/down
 */
@ApiTags('Migration') // Groups endpoints under 'Migration' in Swagger UI
@ApiBearerAuth() // Indicates endpoints require authentication
@Controller('migration') // Base route path: /migration
@UseGuards(MigrationGuard) // Protect all endpoints with migration guard
export class MigrationController {
  /**
   * Creates an instance of MigrationController
   *
   * @param migrationService - MigrationService for database migration operations
   */
  constructor(private readonly migrationService: MigrationService) {}

  /**
   * Execute database migrations (up)
   *
   * Applies pending database migrations to bring the database schema
   * up to date with the latest version. This should be run during
   * deployments or when new migrations are added.
   *
   * Typical migration flow:
   * 1. Check for pending migrations
   * 2. Execute each migration in transaction
   * 3. Update migrations table
   * 4. Log results and any errors
   *
   * @returns Migration execution results (success/failure, details)
   *
   * @throws 401 - Unauthorized (if MigrationGuard rejects request)
   * @throws 500 - Internal server error (if migration fails)
   *
   * @note Should be disabled or heavily restricted in production
   * @note Consider adding dry-run option for testing
   */
  @Post('/up')
  @HttpCode(HttpStatus.OK) // Explicitly set 200 OK for successful migration
  @ApiOperation({
    summary: 'Run database migrations',
    description:
      'Execute pending database migrations to update schema to latest version. Requires admin authorization.',
  })
  @ApiResponse({
    status: 200,
    description: 'Migrations executed successfully',
    schema: {
      example: {
        success: true,
        message: 'Migrations completed successfully',
        executedMigrations: ['CreateUsersTable', 'AddEmailIndex'],
        pendingMigrations: 0,
      },
    },
  })
  @ApiResponse({
    status: 401,
    description: 'Unauthorized - Missing or invalid authentication',
  })
  @ApiResponse({
    status: 500,
    description: 'Migration failed - Database error or migration script error',
    schema: {
      example: {
        success: false,
        error: 'SQL error: column "email" already exists',
        failedMigration: 'AddEmailColumn',
      },
    },
  })
  up() {
    return this.migrationService.migrateUp();
  }

  /**
   * Rollback database migrations (down) - COMMENTED OUT FOR SAFETY
   *
   * This endpoint is intentionally commented out to prevent accidental
   * rollbacks which could cause data loss. If needed, it should be
   * carefully controlled and only accessible to senior administrators.
   *
   * Consider implementing with additional safeguards:
   * - Confirmation step with token
   * - Backup creation before rollback
   * - Environment restrictions (never in production)
   * - Limit to rolling back only the last migration
   */
  // @Post('/down')
  // @ApiOperation({
  //   summary: 'Rollback last migration',
  //   description: 'WARNING: Rollback the most recent database migration. Use with extreme caution.'
  // })
  // @ApiResponse({
  //   status: 200,
  //   description: 'Migration rolled back successfully',
  //   schema: {
  //     example: {
  //       success: true,
  //       message: 'Migration rolled back successfully',
  //       rolledBackMigration: 'AddEmailColumn'
  //     }
  //   }
  // })
  // @ApiResponse({
  //   status: 401,
  //   description: 'Unauthorized'
  // })
  // down() {
  //   return this.migrationService.migrateDown();
  // }

  /**
   * Additional migration endpoints that could be added:
   *
   * @Get('status')
   * getMigrationStatus() {
   *   return this.migrationService.getMigrationStatus();
   * }
   *
   * @Post('reset')
   * @UseGuards(SuperAdminGuard) // Extra protection for dangerous operations
   * resetMigrations() {
   *   return this.migrationService.resetMigrations();
   * }
   *
   * @Post('create')
   * @UseGuards(DeveloperGuard)
   * createMigration(@Body() createDto: CreateMigrationDto) {
   *   return this.migrationService.createMigration(createDto);
   * }
   */
}
