package com.saas.admin.controller;

import com.saas.admin.service.AdminToTenantDataMigrationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * Admin Data Migration Controller
 * 
 * Triggers one-time data migration from admin DB to tenant DBs
 * Phase 1.4 of Admin/Tenant architecture refactoring
 * 
 * SECURITY: Only SYSTEM_ADMIN can trigger migrations
 */
@RestController
@RequestMapping("/api/admin/migration")
@PreAuthorize("hasRole('SYSTEM_ADMIN')")
@Tag(name = "Admin Migration", description = "Data migration admin → tenant")
@Slf4j
@RequiredArgsConstructor
public class AdminDataMigrationController {
    
    private final AdminToTenantDataMigrationService migrationService;
    
    @PostMapping("/tenant/{tenantId}")
    @Operation(summary = "Migrate data for specific tenant")
    public ResponseEntity<?> migrateTenant(@PathVariable String tenantId) {
        log.info("🔄 Admin triggered migration for tenant: {}", tenantId);
        
        try {
            AdminToTenantDataMigrationService.MigrationResult result = 
                migrationService.migrateAllDataForTenant(tenantId);
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("❌ Migration failed for tenant: {}", tenantId, e);
            return ResponseEntity.internalServerError()
                .body("Migration failed: " + e.getMessage());
        }
    }
    
    @PostMapping("/all-tenants")
    @Operation(summary = "Migrate data for ALL tenants")
    public ResponseEntity<?> migrateAllTenants() {
        log.warn("🚨 Admin triggered migration for ALL tenants");
        
        try {
            AdminToTenantDataMigrationService.MigrationSummary summary = 
                migrationService.migrateAllTenants();
            
            return ResponseEntity.ok(summary);
            
        } catch (Exception e) {
            log.error("❌ Bulk migration failed", e);
            return ResponseEntity.internalServerError()
                .body("Bulk migration failed: " + e.getMessage());
        }
    }
}
