<?php

namespace App\Http\Controllers\Api\Utilities;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Utilities\PhoneFormatRequest;
use App\Http\Resources\Utilities\PhoneFormatResource;
use App\Services\Phone\PhoneFormatterService;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

class PhoneFormatterController extends BaseApiController
{
    public function __construct(private PhoneFormatterService $service)
    {
        parent::__construct();
    }

    public function format(PhoneFormatRequest $request): JsonResponse
    {
        $raw = (string) $request->validated()['number'];
        $formatted = $this->service->format($raw);

        if ($formatted === null) {
            return $this->error('Invalid phone number.', Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        return $this->success([
            'phone' => new PhoneFormatResource([
                'raw' => $raw,
                'formatted' => $formatted,
                'is_valid' => true,
            ]),
        ]);
    }
}
