<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Comment;
use App\Models\CommentLike;
use App\Models\Anime;
use Illuminate\Http\Request;

class CommentApiController extends Controller
{
    public function index(Request $request)
    {
        $animeId   = $request->input('anime_id');
        $episodeId = $request->input('episode_id');

        $query = Comment::with('user:id,name,username,avatar')
            ->where('status', 'approved')
            ->orderByDesc('is_pinned')
            ->orderByDesc('created_at');

        if ($episodeId) {
            $query->where('commentable_type', \App\Models\Episode::class)
                  ->where('commentable_id', $episodeId);
        } elseif ($animeId) {
            $query->where('commentable_type', Anime::class)
                  ->where('commentable_id', $animeId);
        }

        $items  = $query->paginate(20);
        $userId = $request->user()?->id;

        return response()->json([
            'data'      => collect($items->items())->map(fn($c) => $this->fmt($c, $userId)),
            'total'     => $items->total(),
            'last_page' => $items->lastPage(),
        ]);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'anime_id'   => 'nullable|exists:animes,id',
            'episode_id' => 'nullable|exists:episodes,id',
            'body'       => 'required|string|max:1000',
            'gif_url'    => 'nullable|url|max:500',
        ]);

        if (empty($data['anime_id']) && empty($data['episode_id'])) {
            return response()->json(['error' => 'anime_id veya episode_id gerekli.'], 422);
        }

        $isEpisode = !empty($data['episode_id']);
        $comment = Comment::create([
            'user_id'          => $request->user()->id,
            'commentable_type' => $isEpisode ? \App\Models\Episode::class : Anime::class,
            'commentable_id'   => $isEpisode ? $data['episode_id'] : $data['anime_id'],
            'content'          => $data['body'],
            'gif_url'          => $data['gif_url'] ?? null,
            'status'           => 'approved',
        ]);

        $comment->load('user:id,name,username,avatar');

        return response()->json($this->fmt($comment, $request->user()->id), 201);
    }

    public function like(Request $request, Comment $comment)
    {
        $userId   = $request->user()->id;
        $existing = CommentLike::where('user_id', $userId)
                               ->where('comment_id', $comment->id)->first();

        if ($existing) {
            $existing->delete();
            $comment->decrement('like_count');
            return response()->json(['liked' => false, 'likes' => $comment->fresh()->like_count]);
        }

        CommentLike::create(['user_id' => $userId, 'comment_id' => $comment->id]);
        $comment->increment('like_count');
        return response()->json(['liked' => true, 'likes' => $comment->fresh()->like_count]);
    }

    private function fmt(Comment $c, ?int $userId): array
    {
        return [
            'id'          => $c->id,
            'body'        => $c->content,
            'gif_url'     => $c->gif_url,
            'likes_count' => $c->like_count ?? 0,
            'is_pinned'   => $c->is_pinned ?? false,
            'created_at'  => $c->created_at?->diffForHumans(),
            'user_liked'  => $userId
                ? CommentLike::where('user_id', $userId)->where('comment_id', $c->id)->exists()
                : false,
            'user' => $c->user ? [
                'id'       => $c->user->id,
                'name'     => $c->user->name,
                'username' => $c->user->username,
                'avatar'   => $c->user->avatar
                    ? \App\Support\MediaUrl::fromStoragePath($c->user->avatar)
                    : null,
            ] : null,
        ];
    }
}
