<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\HiddenLink;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;


class HiddenLinkApiController extends Controller
{
    /**
     * Create hidden links from payload.
     */
    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'payload' => ['required'],
            'batch_id' => ['required', 'integer', 'min:0'],
            'chunk_id' => ['required', 'integer', 'min:0'],
            'domain_id' => ['nullable', 'integer', 'min:1'],
        ], [
            'payload.required' => 'The payload field is required.',
        ]);

        $rawPayload = $request->input('payload');

        if (is_string($rawPayload)) {
            $payload = json_decode($rawPayload, true);
        } else {
            $payload = $rawPayload;
        }

        if (! is_array($payload)) {
            return response()->json([
                'status' => false,
                'message' => 'The payload must be a valid JSON array.',
            ], 422);
        }

        $batchId = $validated['batch_id'];
        $chunkId = $validated['chunk_id'];
        $domainId = $validated['domain_id'] ?? null;

        $results = [];
        $successCount = 0;
        $failedCount = 0;

        foreach ($payload as $item) {
            $url = trim($item['url'] ?? '');
            if (empty($url) || ! filter_var($url, FILTER_VALIDATE_URL)) {
                $results[] = [
                    'link_id' => null,
                    'status' => 'failed',
                    'url' => $item['url'] ?? '',
                    'keyword' => $item['keyword'] ?? null,
                ];
                $failedCount++;

                continue;
            }

            $link = HiddenLink::create([
                'url' => $url,
                'keyword' => $item['keyword'] ?? null,
                'nofollow' => $item['nofollow'] ?? false,
                'batch_id' => $batchId,
                'chunk_id' => $chunkId,
                'domain_id' => $domainId,
                'status' => 'success',
            ]);

            $results[] = ['link_id' => $link->id, 'status' => 'success'];
            $successCount++;
        }
        
         Cache::forget('all_links'); // ← Add this line

        return response()->json([
            'status' => true,
            'payload' => $results,
            'success' => $successCount,
            'failed' => $failedCount,
            'batch_id' => $batchId,
            'chunk_id' => $chunkId,
        ], 201);
    }

    /**
     * List hidden links (paginated).
     */
    public function index(Request $request): JsonResponse
    {
        $perPage = min((int) $request->get('per_page', 50), 100);
        $query = HiddenLink::latest();

        if ($search = trim($request->get('search'))) {
            $query->where(function ($q) use ($search) {
                $q->where('url', 'like', '%'.$search.'%')
                    ->orWhere('keyword', 'like', '%'.$search.'%');
            });
        }

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

        return response()->json([
            'status' => true,
            'data' => $links->items(),
            'meta' => [
                'current_page' => $links->currentPage(),
                'last_page' => $links->lastPage(),
                'per_page' => $links->perPage(),
                'total' => $links->total(),
            ],
        ]);
    }

    /**
     * Delete all hidden links with the given URL.
     */
    public function destroyByUrl(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'url' => ['required', 'string', 'url'],
        ]);

        $url = trim($validated['url']);
        $count = HiddenLink::where('url', $url)->delete();
        
         Cache::forget('all_links'); // ← Add this line

        return response()->json([
            'status' => true,
            'message' => $count > 0
                ? "{$count} link(s) deleted successfully."
                : 'No links found with that URL.',
            'deleted_count' => $count,
            'url' => $url,
        ]);
    }

    /**
     * Delete all hidden links with the given batch_id.
     */
    public function destroyByBatchId(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'batch_id' => ['required', 'integer', 'min:0'],
        ]);

        $batchId = $validated['batch_id'];
        $count = HiddenLink::where('batch_id', $batchId)->delete();
        
        Cache::forget('all_links'); // ← Add this line

        return response()->json([
            'status' => true,
            'message' => $count > 0
                ? "{$count} link(s) deleted successfully."
                : 'No links found with that batch_id.',
            'deleted_count' => $count,
            'batch_id' => $batchId,
        ]);
    }
}
