<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\Services\OnboardingService;
use App\Services\ActionNotificationService;

class OnboardController extends Controller
{
    /**
     * Handle onboarding of company, fleet, drivers, and loads in one call.
     * Only company info is required. Others are optional/skippable.
     */
    public function onboard(Request $request, ActionNotificationService $notifications)
    {
        $existingUser = auth('api')->user();
        $data = $request->all();

        if ($existingUser) {
            $data['user']['name'] = $data['user']['name'] ?? $existingUser->name;
            $data['user']['email'] = $data['user']['email'] ?? $existingUser->email;
        }

        $validator = Validator::make($data, [
            'company.name' => 'required|string|max:255',
            'company.email' => ['required', 'email', 'max:255', 'unique:companies,email'],
            'company.phone' => 'nullable|string|max:32',
            'company.address' => 'nullable|string|max:255',
            'company.mc_number' => 'nullable|string|max:32',
            'company.dot_number' => 'nullable|string|max:32',
            'user.name' => 'required|string|max:255',
            'user.email' => [
                'required',
                'email',
                'max:255',
                Rule::unique('users', 'email')->ignore($existingUser?->id),
            ],
            'user.password' => $existingUser ? 'nullable|string|min:8' : 'required|string|min:8',
            'plan' => 'required|string|in:starter',
            'num_trucks' => 'required|integer|min:1',
            'num_drivers' => 'nullable|integer|min:1',
            'fleet' => 'array',
            'fleet.*.number' => 'required_with:fleet|string|max:50',
            'fleet.*.name' => 'required_with:fleet|string|max:100',
            'fleet.*.equipment_number' => 'nullable|string|max:50',
            'fleet.*.fuel_cost_per_mile' => 'nullable|numeric|min:0',
            'drivers' => 'array',
            'drivers.*.name' => 'required_with:drivers|string|max:255',
            'drivers.*.email' => 'nullable|email|max:255',
            'drivers.*.phone' => 'nullable|string|max:20',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        try {
            $service = new OnboardingService();
            $result = $existingUser
                ? $service->onboardForExistingUser($existingUser, $data)
                : $service->onboard($data);

            $notifications->notifyAction(
                'Onboarding Completed',
                $result['user'],
                [
                    'channel' => 'mobile',
                    'company_id' => $result['company']->id,
                    'company_name' => $result['company']->name,
                    'plan' => $result['plan'],
                    'num_trucks' => $result['num_trucks'],
                    'num_drivers' => $result['num_drivers'],
                ]
            );

            return response()->json([
                'message' => 'Onboarding successful',
                'company_id' => $result['company']->id,
                'user_id' => $result['user']->id,
                'plan' => $result['plan'],
                'num_trucks' => $result['num_trucks'],
                'num_drivers' => $result['num_drivers'],
                'total_price' => $result['total_price'],
            ], 201);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Onboarding failed', 'details' => $e->getMessage()], 500);
        }
    }
}
