<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Feed;
use App\Models\Keyword;
use App\Models\PlatformChannel;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class KeywordsController extends BaseController
{
    /**
     * Display keywords for a specific route
     */
    public function index(Feed $feed, PlatformChannel $channel): JsonResponse
    {
        $keywords = Keyword::where('feed_id', $feed->id)
            ->where('platform_channel_id', $channel->id)
            ->orderBy('keyword')
            ->get();

        return $this->sendResponse(
            $keywords->toArray(),
            'Keywords retrieved successfully.'
        );
    }

    /**
     * Store a new keyword for a route
     */
    public function store(Request $request, Feed $feed, PlatformChannel $channel): JsonResponse
    {
        try {
            $validated = $request->validate([
                'keyword' => 'required|string|max:255',
                'is_active' => 'boolean',
            ]);

            $validated['feed_id'] = $feed->id;
            $validated['platform_channel_id'] = $channel->id;
            $validated['is_active'] = $validated['is_active'] ?? true;

            // Check if keyword already exists for this route
            $existingKeyword = Keyword::where('feed_id', $feed->id)
                ->where('platform_channel_id', $channel->id)
                ->where('keyword', $validated['keyword'])
                ->first();

            if ($existingKeyword) {
                return $this->sendError('Keyword already exists for this route.', [], 409);
            }

            $keyword = Keyword::create($validated);

            return $this->sendResponse(
                $keyword->toArray(),
                'Keyword created successfully!',
                201
            );
        } catch (ValidationException $e) {
            return $this->sendValidationError($e->errors());
        } catch (\Exception $e) {
            return $this->sendError('Failed to create keyword: '.$e->getMessage(), [], 500);
        }
    }

    /**
     * Update a keyword's status
     */
    public function update(Request $request, Feed $feed, PlatformChannel $channel, Keyword $keyword): JsonResponse
    {
        try {
            // Verify the keyword belongs to this route
            if ($keyword->feed_id !== $feed->id || $keyword->platform_channel_id !== $channel->id) {
                return $this->sendNotFound('Keyword not found for this route.');
            }

            $validated = $request->validate([
                'is_active' => 'boolean',
            ]);

            $keyword->update($validated);

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

    /**
     * Remove a keyword from a route
     */
    public function destroy(Feed $feed, PlatformChannel $channel, Keyword $keyword): JsonResponse
    {
        try {
            // Verify the keyword belongs to this route
            if ($keyword->feed_id !== $feed->id || $keyword->platform_channel_id !== $channel->id) {
                return $this->sendNotFound('Keyword not found for this route.');
            }

            $keyword->delete();

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

    /**
     * Toggle keyword active status
     */
    public function toggle(Feed $feed, PlatformChannel $channel, Keyword $keyword): JsonResponse
    {
        try {
            // Verify the keyword belongs to this route
            if ($keyword->feed_id !== $feed->id || $keyword->platform_channel_id !== $channel->id) {
                return $this->sendNotFound('Keyword not found for this route.');
            }

            $newStatus = ! $keyword->is_active;
            $keyword->update(['is_active' => $newStatus]);

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

            return $this->sendResponse(
                $keyword->fresh()->toArray(),
                "Keyword {$status} successfully!"
            );
        } catch (\Exception $e) {
            return $this->sendError('Failed to toggle keyword status: '.$e->getMessage(), [], 500);
        }
    }
}
