<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Announcement;
use App\Models\AnnouncementLike;
use App\Models\User;
use Illuminate\Http\Request;

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

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

        $items = $posts->map(fn ($post) => $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 toggleLike(Request $request, $id)
    {
        $user = $request->user();
        $announcement = Announcement::findOrFail($id);
        $like = AnnouncementLike::where('announcement_id', $announcement->id)->where('user_id', $user->id)->first();
        if ($like) {
            $like->delete();
            $liked = false;
        } else {
            AnnouncementLike::create(['announcement_id' => $announcement->id, 'user_id' => $user->id]);
            $liked = true;
        }
        $announcement->loadCount(['likes', 'comments']);
        return response()->json([
            'success' => true,
            'liked' => $liked,
            'like_count' => $announcement->likes_count,
        ]);
    }

    private function resolveUser(Request $request): ?User
    {
        $walletAddress = $request->header('X-Wallet-Address');
        if (!$walletAddress) {
            return null;
        }
        return User::where('wallet_address', strtolower($walletAddress))->where('is_active', true)->first();
    }

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

    private function formatPost(Announcement $post, bool $liked = false): 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(),
        ];
    }
}
