<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Resources\ArticleResource;
use App\Jobs\ArticleDiscoveryJob;
use App\Models\Article;
use App\Models\Setting;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ArticlesController extends BaseController
{
    /**
     * Display a listing of articles
     */
    public function index(Request $request): JsonResponse
    {
        $perPage = min($request->get('per_page', 15), 100); // Max 100 items per page
        $articles = Article::with(['feed', 'articlePublication'])
            ->orderBy('created_at', 'desc')
            ->paginate($perPage);

        $publishingApprovalsEnabled = Setting::isPublishingApprovalsEnabled();

        return $this->sendResponse([
            'articles' => ArticleResource::collection($articles->items()),
            'pagination' => [
                'current_page' => $articles->currentPage(),
                'last_page' => $articles->lastPage(),
                'per_page' => $articles->perPage(),
                'total' => $articles->total(),
                'from' => $articles->firstItem(),
                'to' => $articles->lastItem(),
            ],
            'settings' => [
                'publishing_approvals_enabled' => $publishingApprovalsEnabled,
            ],
        ]);
    }

    /**
     * Manually refresh articles from all active feeds
     */
    public function refresh(): JsonResponse
    {
        try {
            ArticleDiscoveryJob::dispatch();

            return $this->sendResponse(
                null,
                'Article refresh started. New articles will appear shortly.'
            );
        } catch (Exception $e) {
            return $this->sendError('Failed to start article refresh: '.$e->getMessage(), [], 500);
        }
    }
}
