<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Country;
use App\Models\Post;
use Illuminate\Http\Request;

class CountryController extends Controller
{
    // GET /api/countries
    public function index()
    {
        return response()->json(
            Country::active()->with('continent')->withCount('posts')->orderBy('name')->get()
        );
    }

    // GET /api/countries/{slug}
    public function show(string $slug)
    {
        return response()->json(
            Country::where('slug', $slug)->with('continent')->withCount('posts')->firstOrFail()
        );
    }

    // GET /api/countries/{slug}/posts
    public function posts(Request $request, string $slug)
    {
        $country = Country::where('slug', $slug)->firstOrFail();

        $posts = Post::published()
            ->where('country_id', $country->id)
            ->with(['category', 'continent', 'tags'])
            ->when($request->category, fn($q) => $q->forCategory($request->category))
            ->orderByDesc('published_at')
            ->paginate($request->per_page ?? 12);

        return response()->json($posts);
    }
}
