<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\Session;
use App\Core\Database;

class ApiController extends Controller
{
    public function getPosts(Request $request): Response
    {
        $postModel = new \App\Models\Post();
        $posts = $postModel->getLatest(20, 0, 'latest');
        return Response::json($posts);
    }

    public function getPost(Request $request, string $slug): Response
    {
        $postModel = new \App\Models\Post();
        $post = $postModel->findBySlug($slug);
        if (!$post) return Response::json(['error' => 'Not found'], 404);
        return Response::json($post);
    }

    public function getUser(Request $request, string $username): Response
    {
        $userModel = new \App\Models\User();
        $user = $userModel->findByUsername($username);
        if (!$user) return Response::json(['error' => 'Not found'], 404);

        $avatarUrl = \App\Helpers\Asset::avatar($user['avatar'] ?? null, $user['username'], 120);
        $coverUrl = \App\Helpers\Asset::cover($user['cover_image'] ?? null);

        return Response::json([
            'username'    => $user['username'],
            'bio'         => $user['bio'] ?? '',
            'reputation'  => $user['reputation'] ?? 0,
            'avatar_url'  => $avatarUrl,
            'cover_url'   => is_string($coverUrl) && str_starts_with($coverUrl, '/') ? $coverUrl : '',
            'joined_date' => date('M Y', strtotime($user['created_at'])),
        ]);
    }
}
