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

use App\Http\Controllers\Controller;
use App\Models\Continent;

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

    // GET /api/continents/{slug}
    public function show(string $slug)
    {
        $continent = Continent::where('slug', $slug)
            ->with(['countries' => fn($q) => $q->withCount('posts')])
            ->withCount('posts')
            ->firstOrFail();

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

    // GET /api/continents/{slug}/posts
    public function posts(string $slug)
    {
        $continent = Continent::where('slug', $slug)->firstOrFail();

        $posts = \App\Models\Post::published()
            ->where('continent_id', $continent->id)
            ->with(['country', 'category', 'tags'])
            ->orderByDesc('published_at')
            ->paginate(12);

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