package com.social.media.interfaces.web.controller;

import com.social.media.interfaces.web.dto.content.CreateContentRequest;
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 Content management - REFACTORED VERSION
 * All operations now include security validation with userId and companyId
 */
@RestController
@RequestMapping("/api/v1/contents")
public class ContentController {
    
    /**
     * Create a new content
     */
    @PostMapping
    public ResponseEntity<String> createContent(@Valid @RequestBody CreateContentRequest request) {
        var authInfo = getAuthenticatedUserInfo();
        
        // TODO: Implement content creation logic with security validation
        // Use authInfo.userId() and authInfo.companyId() for context
        
        return ResponseEntity.status(HttpStatus.CREATED).body("Content created successfully by user: " + authInfo.userId().value() + " in company: " + authInfo.companyId());
    }
    
    /**
     * Get content by ID with security validation
     */
    @GetMapping("/{id}")
    public ResponseEntity<String> getContent(@PathVariable Long id) {
        var authInfo = getAuthenticatedUserInfo();
        
        // TODO: Implement get content logic with security validation
        // Verify user has access to this content within their company
        
        return ResponseEntity.ok("Content with ID: " + id + " for user: " + authInfo.userId().value() + " in company: " + authInfo.companyId());
    }
    
    /**
     * Get all contents in company with security validation
     */
    @GetMapping
    public ResponseEntity<String> getAllContents() {
        var authInfo = getAuthenticatedUserInfo();
        
        // TODO: Implement get all contents logic with security validation
        // Filter contents by user's company
        
        return ResponseEntity.ok("All contents for user: " + authInfo.userId().value() + " in company: " + authInfo.companyId());
    }
    
    /**
     * Get current user's contents
     */
    @GetMapping("/my-contents")
    public ResponseEntity<String> getMyContents() {
        var authInfo = getAuthenticatedUserInfo();
        
        // TODO: Implement get user's own contents logic
        
        return ResponseEntity.ok("Contents created by user: " + authInfo.userId().value() + " in company: " + authInfo.companyId());
    }
    
    /**
     * Update content with security validation
     */
    @PutMapping("/{id}")
    public ResponseEntity<String> updateContent(@PathVariable Long id, @Valid @RequestBody CreateContentRequest request) {
        var authInfo = getAuthenticatedUserInfo();
        
        // TODO: Implement update content logic with security validation
        // Verify user has access to this content
        
        return ResponseEntity.ok("Content " + id + " updated by user: " + authInfo.userId().value() + " in company: " + authInfo.companyId());
    }
    
    /**
     * Delete content with security validation
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteContent(@PathVariable Long id) {
        var authInfo = getAuthenticatedUserInfo();
        
        // TODO: Implement delete content logic with security validation
        // Verify user has access to this content
        
        return ResponseEntity.ok("Content " + id + " deleted by user: " + authInfo.userId().value() + " in company: " + authInfo.companyId());
    }
    
    /**
     * Get contents by category with security validation
     */
    @GetMapping("/category/{categoryId}")
    public ResponseEntity<String> getContentsByCategory(@PathVariable Long categoryId) {
        var authInfo = getAuthenticatedUserInfo();
        
        // TODO: Implement get contents by category logic with security validation
        
        return ResponseEntity.ok("Contents in category " + categoryId + " for company: " + authInfo.companyId());
    }
    
    /**
     * Health check endpoint
     */
    @GetMapping("/health")
    public ResponseEntity<String> health() {
        return ResponseEntity.ok("Content 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) {}
}
