<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\DiscoverPost;
use App\Models\DiscoverPostLike;
use App\Models\DiscoverPostComment;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class DiscoverController extends Controller
{
    public function index(Request $request)
    {
        $perPage = min(max((int) $request->get('per_page', 15), 5), 30);
        $posts = DiscoverPost::withCount(['likes', 'comments'])
            ->latest()
            ->paginate($perPage);

        $user = $request->user();
        $likedIds = $user ? DiscoverPostLike::where('user_id', $user->id)
            ->whereIn('discover_post_id', $posts->pluck('id'))
            ->pluck('discover_post_id')
            ->flip()
            ->toArray() : [];

        $items = $posts->map(function ($post) use ($likedIds) {
            return $this->formatPost($post, isset($likedIds[$post->id]));
        });

        return response()->json([
            'success' => true,
            'posts' => $items,
            'pagination' => [
                'current_page' => $posts->currentPage(),
                'last_page' => $posts->lastPage(),
                'per_page' => $posts->perPage(),
                'total' => $posts->total(),
            ],
        ]);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'content' => 'required|string|max:5000',
            'image' => 'nullable|image|max:5120',
        ]);
        if ($validator->fails()) {
            return response()->json(['success' => false, 'message' => 'Validation failed', 'errors' => $validator->errors()], 422);
        }

        $user = $request->user();
        $imagePath = null;
        if ($request->hasFile('image')) {
            $imagePath = $request->file('image')->store('discover/posts', 'public');
        }

        $post = DiscoverPost::create([
            'user_id' => $user->id,
            'demo_author_id' => null,
            'content' => $request->content,
            'image_path' => $imagePath,
        ]);

        return response()->json([
            'success' => true,
            'post' => $this->formatPost($post->loadCount(['likes', 'comments']), false),
            'message' => 'Post created',
        ], 201);
    }

    public function toggleLike(Request $request, $id)
    {
        $user = $request->user();
        $post = DiscoverPost::findOrFail($id);
        $like = DiscoverPostLike::where('discover_post_id', $post->id)->where('user_id', $user->id)->first();
        if ($like) {
            $like->delete();
            $liked = false;
        } else {
            DiscoverPostLike::create(['discover_post_id' => $post->id, 'user_id' => $user->id]);
            $liked = true;
        }
        $post->loadCount(['likes', 'comments']);
        return response()->json([
            'success' => true,
            'liked' => $liked,
            'like_count' => $post->likes_count,
            'post' => $this->formatPost($post, $liked),
        ]);
    }

    public function comments(Request $request, $id)
    {
        $post = DiscoverPost::findOrFail($id);
        $comments = $post->comments()->latest()->get()->map(function ($c) {
            return [
                'id' => $c->id,
                'author' => $c->authorDisplay(),
                'body' => $c->body,
                'created_at' => $c->created_at->toIso8601String(),
            ];
        });
        return response()->json(['success' => true, 'comments' => $comments]);
    }

    public function storeComment(Request $request, $id)
    {
        $validator = Validator::make($request->all(), ['body' => 'required|string|max:2000']);
        if ($validator->fails()) {
            return response()->json(['success' => false, 'message' => 'Validation failed', 'errors' => $validator->errors()], 422);
        }
        $user = $request->user();
        $post = DiscoverPost::findOrFail($id);
        $comment = DiscoverPostComment::create([
            'discover_post_id' => $post->id,
            'user_id' => $user->id,
            'author_display' => null,
            'body' => $request->body,
        ]);
        return response()->json([
            'success' => true,
            'comment' => [
                'id' => $comment->id,
                'author' => $comment->authorDisplay(),
                'body' => $comment->body,
                'created_at' => $comment->created_at->toIso8601String(),
            ],
        ], 201);
    }

    private function formatPost(DiscoverPost $post, bool $liked): array
    {
        $imageUrl = null;
        if ($post->image_path) {
            $imageUrl = '/storage/' . $post->image_path;
        }
        return [
            'id' => $post->id,
            'author' => $post->authorDisplay(),
            'content' => $post->content,
            'image_url' => $imageUrl,
            'like_count' => $post->likes_count ?? $post->likes()->count(),
            'comment_count' => $post->comments_count ?? $post->comments()->count(),
            'liked' => $liked,
            'created_at' => $post->created_at->toIso8601String(),
        ];
    }
}
