<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\NumerologyService;
use App\Services\RootInterpretationService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;

class NumerologyController extends Controller
{
    public function __construct(
        private NumerologyService $numerologyService,
        private RootInterpretationService $interpretationService
    ) {}

    public function calculate(Request $request): JsonResponse
    {
        try {
            $validated = $request->validate([
                'name' => 'required|string|max:255',
                'birthdate' => 'required|string',
                'industry' => 'nullable|string|max:255',
            ]);

            $result = $this->numerologyService->performFullCalculation(
                $validated['name'],
                $validated['birthdate'],
                $validated['industry'] ?? null
            );

            return response()->json([
                'success' => true,
                'data' => $result
            ]);

        } catch (ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);

        } catch (\InvalidArgumentException $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
                'error_code' => 'CALC_001'
            ], 400);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Internal server error',
                'error_code' => 'CALC_002'
            ], 500);
        }
    }

    public function getInterpretation(int $rootNumber): JsonResponse
    {
        if ($rootNumber < 1 || $rootNumber > 9) {
            return response()->json([
                'success' => false,
                'message' => 'Root number must be between 1 and 9'
            ], 400);
        }

        $interpretation = $this->interpretationService->getInterpretation($rootNumber);

        if (!$interpretation) {
            return response()->json([
                'success' => false,
                'message' => 'Interpretation not found'
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => $interpretation
        ]);
    }

    public function saveCalculation(Request $request): JsonResponse
    {
        try {
            $validated = $request->validate([
                'calculation' => 'required|array',
                'calculation.name' => 'required|string|max:255',
                'calculation.birthdate' => 'required|date',
                'calculation.industry' => 'nullable|string|max:255',
                'calculation.L5' => 'required|array|size:4',
                'calculation.L6' => 'required|array|size:4',
                'calculation.L7' => 'required|array|size:2',
                'calculation.L8' => 'required|array|size:7',
                'calculation.L9' => 'required|array|size:3',
                'calculation.root_number' => 'required|integer|between:1,9',
                'swot_combinations' => 'nullable|array',
                'interpretation' => 'nullable|array',
                'business_guidance' => 'nullable|array',
                'learning_style' => 'nullable|array',
            ]);

            $user = $request->user();
            $savedCalculation = $this->numerologyService->saveCalculation($validated, $user);

            return response()->json([
                'success' => true,
                'data' => $savedCalculation,
                'message' => 'Calculation saved successfully'
            ], 201);

        } catch (ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to save calculation',
                'error_code' => 'SAVE_001'
            ], 500);
        }
    }

    public function getUserCalculations(Request $request): JsonResponse
    {
        try {
            $user = $request->user();
            $calculations = $this->numerologyService->getUserCalculations($user);

            return response()->json([
                'success' => true,
                'data' => $calculations
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve calculations',
                'error_code' => 'FETCH_001'
            ], 500);
        }
    }

    public function deleteCalculation(Request $request, int $id): JsonResponse
    {
        try {
            $user = $request->user();
            $deleted = $this->numerologyService->deleteCalculation($id, $user);

            if (!$deleted) {
                return response()->json([
                    'success' => false,
                    'message' => 'Calculation not found or unauthorized'
                ], 404);
            }

            return response()->json([
                'success' => true,
                'message' => 'Calculation deleted successfully'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete calculation',
                'error_code' => 'DELETE_001'
            ], 500);
        }
    }
}
