package com.social.media.interfaces.web.controller;

import com.social.media.interfaces.web.dto.bot.CreateBotRequest;
import com.social.media.domain.user.valueobject.UserId;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

/**
 * REST Controller for Bot management - REFACTORED VERSION
 * All operations now include security validation with userId and companyId
 */
@RestController
@RequestMapping("/api/v1/bots")
public class BotController {
    
    /**
     * Create a new bot
     */
    @PostMapping
    public ResponseEntity<String> createBot(@Valid @RequestBody CreateBotRequest request) {
        var authInfo = getAuthenticatedUserInfo();
        
        // TODO: Implement bot creation logic with security validation
        // Use authInfo.userId() and authInfo.companyId() for context
        
        return ResponseEntity.status(HttpStatus.CREATED).body("Bot created successfully by user: " + authInfo.userId().value() + " in company: " + authInfo.companyId());
    }
    
    /**
     * Get bot by ID with security validation
     */
    @GetMapping("/{id}")
    public ResponseEntity<String> getBot(@PathVariable Long id) {
        var authInfo = getAuthenticatedUserInfo();
        
        // TODO: Implement get bot logic with security validation
        // Verify user has access to this bot within their company
        
        return ResponseEntity.ok("Bot with ID: " + id + " for user: " + authInfo.userId().value() + " in company: " + authInfo.companyId());
    }
    
    /**
     * Get bots by company with security validation
     */
    @GetMapping("/company/{companyId}")
    public ResponseEntity<String> getBotsByCompany(@PathVariable Long companyId) {
        var authInfo = getAuthenticatedUserInfo();
        
        // Verify user has access to this company
        if (!authInfo.companyId().equals(companyId)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Access denied to company: " + companyId);
        }
        
        // TODO: Implement get bots by company logic with security validation
        
        return ResponseEntity.ok("Bots for company: " + companyId + " accessed by user: " + authInfo.userId().value());
    }
    
    /**
     * Get all bots in user's company
     */
    @GetMapping
    public ResponseEntity<String> getAllBots() {
        var authInfo = getAuthenticatedUserInfo();
        
        // TODO: Implement get all bots logic with security validation
        // Filter bots by user's company
        
        return ResponseEntity.ok("All bots for user: " + authInfo.userId().value() + " in company: " + authInfo.companyId());
    }
    
    /**
     * Get current user's bots
     */
    @GetMapping("/my-bots")
    public ResponseEntity<String> getMyBots() {
        var authInfo = getAuthenticatedUserInfo();
        
        // TODO: Implement get user's own bots logic
        
        return ResponseEntity.ok("Bots created by user: " + authInfo.userId().value() + " in company: " + authInfo.companyId());
    }
    
    /**
     * Update bot with security validation
     */
    @PutMapping("/{id}")
    public ResponseEntity<String> updateBot(@PathVariable Long id, @Valid @RequestBody CreateBotRequest request) {
        var authInfo = getAuthenticatedUserInfo();
        
        // TODO: Implement update bot logic with security validation
        // Verify user has access to this bot
        
        return ResponseEntity.ok("Bot " + id + " updated by user: " + authInfo.userId().value() + " in company: " + authInfo.companyId());
    }
    
    /**
     * Delete bot with security validation
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteBot(@PathVariable Long id) {
        var authInfo = getAuthenticatedUserInfo();
        
        // TODO: Implement delete bot logic with security validation
        // Verify user has access to this bot
        
        return ResponseEntity.ok("Bot " + id + " deleted by user: " + authInfo.userId().value() + " in company: " + authInfo.companyId());
    }
    
    /**
     * Start bot with security validation
     */
    @PostMapping("/{id}/start")
    public ResponseEntity<String> startBot(@PathVariable Long id) {
        var authInfo = getAuthenticatedUserInfo();
        
        // TODO: Implement start bot logic with security validation
        // Verify user has access to this bot
        
        return ResponseEntity.ok("Bot " + id + " started successfully by user: " + authInfo.userId().value() + " in company: " + authInfo.companyId());
    }
    
    /**
     * Stop bot with security validation
     */
    @PostMapping("/{id}/stop")
    public ResponseEntity<String> stopBot(@PathVariable Long id) {
        var authInfo = getAuthenticatedUserInfo();
        
        // TODO: Implement stop bot logic with security validation
        // Verify user has access to this bot
        
        return ResponseEntity.ok("Bot " + id + " stopped successfully by user: " + authInfo.userId().value() + " in company: " + authInfo.companyId());
    }
    
    /**
     * Health check endpoint
     */
    @GetMapping("/health")
    public ResponseEntity<String> health() {
        return ResponseEntity.ok("Bot service is healthy");
    }
    
    /**
     * Helper method to get authenticated user information
     */
    private AuthenticatedUserInfo getAuthenticatedUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new RuntimeException("User not authenticated");
        }
        
        // Extract user ID and company ID from authentication
        Long userId = extractUserIdFromAuthentication(authentication);
        Long companyId = extractCompanyIdFromAuthentication(authentication);
        
        return new AuthenticatedUserInfo(UserId.of(userId), companyId);
    }
    
    private Long extractUserIdFromAuthentication(Authentication authentication) {
        // TODO: Implement based on your JWT/session structure
        return 1L; // Temporary
    }
    
    private Long extractCompanyIdFromAuthentication(Authentication authentication) {
        // TODO: Implement based on your JWT/session structure
        return 1L; // Temporary
    }
    
    /**
     * Record to hold authenticated user information
     */
    private record AuthenticatedUserInfo(UserId userId, Long companyId) {}
}
