package com.social.media.controller;

import com.social.media.dto.PostDto;
import com.social.media.service.PostService;
import com.social.media.domain.shared.PageResponse;
import com.social.media.domain.entity.Post;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.format.annotation.DateTimeFormat;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/api/posts")
public class PostController {
    
    @Autowired
    private PostService postService;
    
    @GetMapping
    public ResponseEntity<PageResponse<PostDto>> getAllPosts(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        PageResponse<PostDto> posts = postService.getAllPosts(page, size);
        return ResponseEntity.ok(posts);
    }
    
    // New endpoint for Long IDs
    @GetMapping("/id/{id}")
    public ResponseEntity<PostDto> getPostByLongId(@PathVariable Long id) {
        PostDto post = postService.getPostById(id);
        return ResponseEntity.ok(post);
    }
    
    // Legacy endpoint maintaining String ID support
    @GetMapping("/{id}")
    public ResponseEntity<PostDto> getPostById(@PathVariable String id) {
        PostDto post;
        try {
            // Try to parse as Long first
            post = postService.getPostById(Long.parseLong(id));
        } catch (NumberFormatException e) {
            // If parsing fails, try as post code
            post = postService.getPostByPostCode(id);
        }
        return ResponseEntity.ok(post);
    }
    
    @GetMapping("/code/{postCode}")
    public ResponseEntity<PostDto> getPostByCode(@PathVariable String postCode) {
        PostDto post = postService.getPostByPostCode(postCode);
        return ResponseEntity.ok(post);
    }
    
    @PostMapping
    public ResponseEntity<PostDto> createPost(@Valid @RequestBody PostDto postDto) {
        PostDto createdPost = postService.createPost(postDto);
        return ResponseEntity.status(HttpStatus.CREATED).body(createdPost);
    }
    
    // New endpoint for Long IDs
    @PutMapping("/id/{id}")
    public ResponseEntity<PostDto> updatePostByLongId(@PathVariable Long id, @Valid @RequestBody PostDto postDto) {
        PostDto updatedPost = postService.updatePost(id, postDto);
        return ResponseEntity.ok(updatedPost);
    }
    
    // Legacy endpoint maintaining String ID support
    @PutMapping("/{id}")
    public ResponseEntity<PostDto> updatePost(@PathVariable String id, @Valid @RequestBody PostDto postDto) {
        PostDto updatedPost = postService.updatePost(id, postDto);
        return ResponseEntity.ok(updatedPost);
    }
    
    // New endpoint for Long IDs
    @DeleteMapping("/id/{id}")
    public ResponseEntity<Void> deletePostByLongId(@PathVariable Long id) {
        postService.deletePost(id);
        return ResponseEntity.noContent().build();
    }
    
    // Legacy endpoint maintaining String ID support
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deletePost(@PathVariable String id) {
        postService.deletePost(id);
        return ResponseEntity.noContent().build();
    }
    
    // Company-specific endpoints
    @GetMapping("/company/{companyId}")
    public ResponseEntity<PageResponse<PostDto>> getPostsByCompany(
            @PathVariable Long companyId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        PageResponse<PostDto> posts = postService.getPostsByCompany(companyId, page, size);
        return ResponseEntity.ok(posts);
    }
    
    @GetMapping("/author/{authorId}")
    public ResponseEntity<PageResponse<PostDto>> getPostsByAuthor(
            @PathVariable Long authorId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        PageResponse<PostDto> posts = postService.getPostsByAuthor(authorId, page, size);
        return ResponseEntity.ok(posts);
    }
    
    @GetMapping("/company/{companyId}/status/{status}")
    public ResponseEntity<PageResponse<PostDto>> getPostsByCompanyAndStatus(
            @PathVariable Long companyId,
            @PathVariable String status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Post.PostStatus postStatus = Post.PostStatus.valueOf(status.toUpperCase());
        PageResponse<PostDto> posts = postService.getPostsByCompanyAndStatus(companyId, postStatus, page, size);
        return ResponseEntity.ok(posts);
    }
    
    @GetMapping("/company/{companyId}/pinned")
    public ResponseEntity<PageResponse<PostDto>> getPinnedPosts(
            @PathVariable Long companyId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        PageResponse<PostDto> posts = postService.getPinnedPosts(companyId, page, size);
        return ResponseEntity.ok(posts);
    }
    
    @GetMapping("/company/{companyId}/popular")
    public ResponseEntity<PageResponse<PostDto>> getPopularPosts(
            @PathVariable Long companyId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        PageResponse<PostDto> posts = postService.getPopularPosts(companyId, page, size);
        return ResponseEntity.ok(posts);
    }
    
    @GetMapping("/company/{companyId}/search")
    public ResponseEntity<PageResponse<PostDto>> searchPosts(
            @PathVariable Long companyId,
            @RequestParam String query,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        PageResponse<PostDto> posts = postService.searchPosts(companyId, query, page, size);
        return ResponseEntity.ok(posts);
    }
    
    // Post actions
    @PatchMapping("/{id}/publish")
    public ResponseEntity<PostDto> publishPost(@PathVariable Long id) {
        PostDto post = postService.publishPost(id);
        return ResponseEntity.ok(post);
    }
    
    @PatchMapping("/{id}/schedule")
    public ResponseEntity<PostDto> schedulePost(
            @PathVariable Long id,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime scheduledTime) {
        PostDto post = postService.schedulePost(id, scheduledTime);
        return ResponseEntity.ok(post);
    }
    
    @PatchMapping("/{id}/pin")
    public ResponseEntity<PostDto> pinPost(@PathVariable Long id) {
        PostDto post = postService.pinPost(id);
        return ResponseEntity.ok(post);
    }
    
    @PatchMapping("/{id}/unpin")
    public ResponseEntity<PostDto> unpinPost(@PathVariable Long id) {
        PostDto post = postService.unpinPost(id);
        return ResponseEntity.ok(post);
    }
    
    // Analytics endpoints
    @GetMapping("/company/{companyId}/analytics/engagement")
    public ResponseEntity<Long> getTotalEngagement(@PathVariable Long companyId) {
        Long engagement = postService.getTotalEngagement(companyId);
        return ResponseEntity.ok(engagement);
    }
    
    @GetMapping("/company/{companyId}/analytics/count")
    public ResponseEntity<Long> getPostCount(@PathVariable Long companyId) {
        Long count = postService.getPostCount(companyId);
        return ResponseEntity.ok(count);
    }
    
    @GetMapping("/company/{companyId}/analytics/count/{status}")
    public ResponseEntity<Long> getPostCountByStatus(
            @PathVariable Long companyId,
            @PathVariable String status) {
        Post.PostStatus postStatus = Post.PostStatus.valueOf(status.toUpperCase());
        Long count = postService.getPostCountByStatus(companyId, postStatus);
        return ResponseEntity.ok(count);
    }
    
    // Scheduled posts management
    @GetMapping("/scheduled/ready")
    public ResponseEntity<List<PostDto>> getScheduledPostsForExecution() {
        List<PostDto> posts = postService.getScheduledPostsForExecution();
        return ResponseEntity.ok(posts);
    }
    
    // Legacy endpoints for backward compatibility
    @GetMapping("/platform/{platform}")
    public ResponseEntity<PageResponse<PostDto>> getPostsByPlatform(
            @PathVariable String platform,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        PageResponse<PostDto> posts = postService.getPostsByPlatform(platform, page, size);
        return ResponseEntity.ok(posts);
    }
    
    @GetMapping("/status/{status}")
    public ResponseEntity<PageResponse<PostDto>> getPostsByStatus(
            @PathVariable String status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        PageResponse<PostDto> posts = postService.getPostsByStatus(status, page, size);
        return ResponseEntity.ok(posts);
    }
    
    @GetMapping("/type/{type}")
    public ResponseEntity<PageResponse<PostDto>> getPostsByType(
            @PathVariable String type,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Post.PostType postType = Post.PostType.valueOf(type.toUpperCase());
        PageResponse<PostDto> posts = postService.getPostsByType(postType, page, size);
        return ResponseEntity.ok(posts);
    }
}
