<?php

namespace App\Http\Controllers\Api\V1;

use App\Actions\CreateFeedAction;
use App\Http\Requests\StoreFeedRequest;
use App\Http\Requests\UpdateFeedRequest;
use App\Http\Resources\FeedResource;
use App\Models\Feed;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;

class FeedsController extends BaseController
{
    /**
     * Display a listing of feeds
     */
    public function index(Request $request): JsonResponse
    {
        $perPage = min($request->get('per_page', 15), 100);

        $feeds = Feed::with(['language'])
            ->withCount('articles')
            ->orderBy('is_active', 'desc')
            ->orderBy('name')
            ->paginate($perPage);

        return $this->sendResponse([
            'feeds' => FeedResource::collection($feeds->items()),
            'pagination' => [
                'current_page' => $feeds->currentPage(),
                'last_page' => $feeds->lastPage(),
                'per_page' => $feeds->perPage(),
                'total' => $feeds->total(),
                'from' => $feeds->firstItem(),
                'to' => $feeds->lastItem(),
            ],
        ], 'Feeds retrieved successfully.');
    }

    /**
     * Store a newly created feed
     */
    public function store(StoreFeedRequest $request, CreateFeedAction $createFeedAction): JsonResponse
    {
        try {
            $validated = $request->validated();

            $feed = $createFeedAction->execute(
                $validated['name'],
                $validated['provider'],
                $validated['language_id'],
                $validated['description'] ?? null,
            );

            return $this->sendResponse(
                new FeedResource($feed),
                'Feed created successfully!',
                201
            );
        } catch (InvalidArgumentException $e) {
            return $this->sendError($e->getMessage(), [], 422);
        } catch (Exception $e) {
            return $this->sendError('Failed to create feed: '.$e->getMessage(), [], 500);
        }
    }

    /**
     * Display the specified feed
     */
    public function show(Feed $feed): JsonResponse
    {
        return $this->sendResponse(
            new FeedResource($feed),
            'Feed retrieved successfully.'
        );
    }

    /**
     * Update the specified feed
     */
    public function update(UpdateFeedRequest $request, Feed $feed): JsonResponse
    {
        try {
            $validated = $request->validated();
            $validated['is_active'] = $validated['is_active'] ?? $feed->is_active;

            $feed->update($validated);

            return $this->sendResponse(
                new FeedResource($feed->fresh()),
                'Feed updated successfully!'
            );
        } catch (ValidationException $e) {
            return $this->sendValidationError($e->errors());
        } catch (Exception $e) {
            return $this->sendError('Failed to update feed: '.$e->getMessage(), [], 500);
        }
    }

    /**
     * Remove the specified feed
     */
    public function destroy(Feed $feed): JsonResponse
    {
        try {
            $feed->delete();

            return $this->sendResponse(
                null,
                'Feed deleted successfully!'
            );
        } catch (Exception $e) {
            return $this->sendError('Failed to delete feed: '.$e->getMessage(), [], 500);
        }
    }

    /**
     * Toggle feed active status
     */
    public function toggle(Feed $feed): JsonResponse
    {
        try {
            $newStatus = ! $feed->is_active;
            $feed->update(['is_active' => $newStatus]);

            $status = $newStatus ? 'activated' : 'deactivated';

            return $this->sendResponse(
                new FeedResource($feed->fresh()),
                "Feed {$status} successfully!"
            );
        } catch (Exception $e) {
            return $this->sendError('Failed to toggle feed status: '.$e->getMessage(), [], 500);
        }
    }
}
