<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Services\PhoneProcessingService;
use Illuminate\Http\Request;

class RefineController extends Controller
{
    public function __construct(private PhoneProcessingService $processor) {}

    /**
     * POST /api/refine — inline quick refine (authenticated tenant)
     */
    public function refine(Request $request)
    {
        $tenant = $request->input('_tenant') ?? $request->user()->tenant;

        // Check plan allows this
        if ($tenant->hasExceededMonthlyLimit()) {
            return response()->json(['error' => 'Monthly limit reached.'], 429);
        }

        $validated = $request->validate([
            'numbers'         => 'required|array|max:500',
            'numbers.*'       => 'required|string|max:50',
            'default_country' => 'nullable|string|size:2',
        ]);

        ['results' => $results, 'summary' => $summary] = $this->processor->processBatch(
            $validated['numbers'],
            $validated['default_country'] ?? 'PK'
        );

        return response()->json(compact('results', 'summary'));
    }

    /**
     * POST /api/v1/refine — external API key route
     */
    public function apiRefine(Request $request)
    {
        $validated = $request->validate([
            'numbers'         => 'required|array|max:10000',
            'numbers.*'       => 'required|string|max:50',
            'default_country' => 'nullable|string|size:2',
        ]);

        ['results' => $results, 'summary' => $summary] = $this->processor->processBatch(
            $validated['numbers'],
            $validated['default_country'] ?? 'PK'
        );

        return response()->json(compact('results', 'summary'));
    }

    /**
     * POST /api/v1/validate — single number validation
     */
    public function apiValidate(Request $request)
    {
        $validated = $request->validate([
            'number'          => 'required|string|max:50',
            'default_country' => 'nullable|string|size:2',
        ]);

        $result = $this->processor->processOne(
            $validated['number'],
            $validated['default_country'] ?? 'PK'
        );

        return response()->json($result);
    }
}
