<?php

namespace App\Http\Controllers;

use App\Actions\Contact\SubmitContactForm;
use App\Actions\Support\ApiRateLimitedException;
use App\Actions\Support\ApiValidationException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Throwable;

/**
 * Port of the legacy `api/submit-contact.php` endpoint.
 *
 * Kept thin: all validation, storage, and notification logic lives in
 * {@see SubmitContactForm}. This controller's only job is translating the
 * action's outcome into the exact legacy JSON response shape — a single
 * flat `message` string, never Laravel's default per-field `errors` object.
 */
class ContactSubmissionController extends Controller
{
    public function __construct(private readonly SubmitContactForm $submitContactForm)
    {
        //
    }

    public function __invoke(Request $request): JsonResponse
    {
        try {
            $result = $this->submitContactForm->handle($request);

            return $this->success($result['submissionId']);
        } catch (ApiRateLimitedException $e) {
            return $this->failure($e->getMessage(), 429);
        } catch (ApiValidationException $e) {
            return $this->failure($e->getMessage(), 422);
        } catch (Throwable $e) {
            Log::error('Contact submission failed', ['exception' => $e->getMessage()]);

            return $this->failure('An error occurred. Please try again or call us at 9879991799.', 500);
        }
    }

    private function success(?int $submissionId): JsonResponse
    {
        $payload = [
            'success' => true,
            'message' => 'Thank you for contacting us! We will get back to you within 24 hours.',
            'timestamp' => now()->format('Y-m-d H:i:s'),
        ];

        if ($submissionId !== null) {
            $payload['submissionId'] = $submissionId;
        }

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

    private function failure(string $message, int $status): JsonResponse
    {
        return response()->json([
            'success' => false,
            'message' => $message,
            'timestamp' => now()->format('Y-m-d H:i:s'),
        ], $status);
    }
}
