<?php

namespace App\Http\Controllers\Api\V1;

use App\Enums\ApprovalStatusEnum;
use App\Http\Resources\RouteArticleResource;
use App\Models\RouteArticle;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class RouteArticlesController extends BaseController
{
    public function index(Request $request): JsonResponse
    {
        $perPage = min($request->get('per_page', 15), 100);

        $query = RouteArticle::with(['article.feed', 'feed', 'platformChannel'])
            ->orderBy('created_at', 'desc');

        if ($request->has('status')) {
            $status = ApprovalStatusEnum::tryFrom($request->get('status'));
            if ($status) {
                $query->where('approval_status', $status);
            }
        }

        $routeArticles = $query->paginate($perPage);

        return $this->sendResponse([
            'route_articles' => RouteArticleResource::collection($routeArticles->items()),
            'pagination' => [
                'current_page' => $routeArticles->currentPage(),
                'last_page' => $routeArticles->lastPage(),
                'per_page' => $routeArticles->perPage(),
                'total' => $routeArticles->total(),
                'from' => $routeArticles->firstItem(),
                'to' => $routeArticles->lastItem(),
            ],
        ]);
    }

    public function approve(RouteArticle $routeArticle): JsonResponse
    {
        try {
            $routeArticle->approve();

            return $this->sendResponse(
                new RouteArticleResource($routeArticle->fresh(['article.feed', 'feed', 'platformChannel'])),
                'Route article approved and queued for publishing.'
            );
        } catch (Exception $e) {
            return $this->sendError('Failed to approve route article: '.$e->getMessage(), [], 500);
        }
    }

    public function reject(RouteArticle $routeArticle): JsonResponse
    {
        try {
            $routeArticle->reject();

            return $this->sendResponse(
                new RouteArticleResource($routeArticle->fresh(['article.feed', 'feed', 'platformChannel'])),
                'Route article rejected.'
            );
        } catch (Exception $e) {
            return $this->sendError('Failed to reject route article: '.$e->getMessage(), [], 500);
        }
    }

    public function restore(RouteArticle $routeArticle): JsonResponse
    {
        try {
            $routeArticle->update([
                'approval_status' => ApprovalStatusEnum::PENDING,
                'decided_at' => null,
            ]);

            return $this->sendResponse(
                new RouteArticleResource($routeArticle->fresh(['article.feed', 'feed', 'platformChannel'])),
                'Route article restored to pending.'
            );
        } catch (Exception $e) {
            return $this->sendError('Failed to restore route article: '.$e->getMessage(), [], 500);
        }
    }

    public function clear(): JsonResponse
    {
        try {
            $count = RouteArticle::where('approval_status', ApprovalStatusEnum::PENDING)->count();

            RouteArticle::where('approval_status', ApprovalStatusEnum::PENDING)
                ->update([
                    'approval_status' => ApprovalStatusEnum::REJECTED,
                    'decided_at' => now(),
                ]);

            return $this->sendResponse(
                ['rejected_count' => $count],
                "Rejected {$count} pending route articles."
            );
        } catch (Exception $e) {
            return $this->sendError('Failed to clear pending route articles: '.$e->getMessage(), [], 500);
        }
    }
}
