<?php

namespace App\Http\Controllers\Api\Auth;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Resources\Auth\RegisterResource;
use App\Services\Auth\RegistrationCaptchaService;
use App\Services\Auth\RegistrationService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class RegisterController extends BaseApiController
{
    public function __construct(
        private RegistrationService $service,
        private RegistrationCaptchaService $captchaService
    ) {
        parent::__construct();
    }

    public function captcha(): JsonResponse
    {
        $captcha = $this->captchaService->generate();

        return response()->json([
            'ok' => true,
            'captcha' => $captcha,
        ]);
    }

    public function store(Request $request): JsonResponse
    {
        if (app()->runningUnitTests() && $request->header('X-Debug-Request') === '1') {
            return response()->json([
                'ok' => true,
                'debug' => [
                    'content_type' => $request->header('Content-Type'),
                    'content_length' => strlen((string) $request->getContent()),
                    'request_all' => $request->all(),
                    'json_all' => $request->json()->all(),
                    'payload_data' => $this->payloadData(),
                ],
            ]);
        }

        $validator = Validator::make($request->all(), \App\Http\Requests\Auth\RegisterRequest::ruleset());
        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }

        $result = $this->service->register($validator->validated());

        if (empty($result['ok'])) {
            $code = $result['code'] ?? 'registration_failed';
            $status = $code === 'pending_activation' || $code === 'email_exists' ? 409 : 422;

            return response()->json([
                'ok' => false,
                'message' => $result['message'] ?? 'Registration failed.',
                'code' => $code,
            ], $status);
        }

        return response()->json([
            'ok' => true,
            'registration' => new RegisterResource($result),
        ], 201);
    }
}
