<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\Vehicle;
use App\Traits\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use OpenApi\Attributes as OA;

class VehicleController extends Controller
{
    use ApiResponse;

    /**
     * Display a listing of vehicles
     */
    #[OA\Get(
        path: '/api/v1/vehicles',
        summary: 'List all vehicles',
        description: 'Retrieve all vehicles belonging to the authenticated user',
        tags: ['Vehicles'],
        security: [['sanctum' => []]],
        responses: [
            new OA\Response(
                response: 200,
                description: 'Vehicles retrieved successfully',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: true),
                        new OA\Property(property: 'data', type: 'array', items: new OA\Items(type: 'object')),
                        new OA\Property(property: 'message', type: 'string', example: 'Vehicles retrieved successfully'),
                    ]
                )
            ),
            new OA\Response(
                response: 401,
                description: 'Unauthorized',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: false),
                        new OA\Property(property: 'message', type: 'string', example: 'Unauthorized'),
                    ]
                )
            ),
        ]
    )]
    public function index(Request $request): JsonResponse
    {
        $vehicles = $request->user()->vehicles;
        return $this->successResponse($vehicles, 'Vehicles retrieved successfully');
    }

    /**
     * Store a newly created vehicle
     */
    #[OA\Post(
        path: '/api/v1/vehicles',
        summary: 'Create a new vehicle',
        description: 'Register a new vehicle for the authenticated user',
        tags: ['Vehicles'],
        security: [['sanctum' => []]],
        requestBody: new OA\RequestBody(
            required: true,
            content: new OA\JsonContent(
                required: ['type', 'make', 'model', 'registration_number'],
                properties: [
                    new OA\Property(property: 'type', type: 'string', enum: ['car', 'van', 'scooter', 'motorbike'], example: 'car'),
                    new OA\Property(property: 'make', type: 'string', example: 'Toyota'),
                    new OA\Property(property: 'model', type: 'string', example: 'Corolla'),
                    new OA\Property(property: 'registration_number', type: 'string', example: 'AB12 CDE'),
                    new OA\Property(property: 'year', type: 'integer', nullable: true, example: 2020),
                    new OA\Property(property: 'color', type: 'string', nullable: true, example: 'Blue'),
                ]
            )
        ),
        responses: [
            new OA\Response(
                response: 201,
                description: 'Vehicle created successfully',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: true),
                        new OA\Property(property: 'data', type: 'object'),
                        new OA\Property(property: 'message', type: 'string', example: 'Vehicle created successfully'),
                    ]
                )
            ),
            new OA\Response(
                response: 401,
                description: 'Unauthorized',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: false),
                        new OA\Property(property: 'message', type: 'string', example: 'Unauthorized'),
                    ]
                )
            ),
            new OA\Response(
                response: 422,
                description: 'Validation error',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: false),
                        new OA\Property(property: 'message', type: 'string', example: 'Validation failed'),
                        new OA\Property(property: 'errors', type: 'object'),
                    ]
                )
            ),
        ]
    )]
    public function store(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'type' => 'required|in:car,van,scooter,motorbike',
            'make' => 'required|string|max:255',
            'model' => 'required|string|max:255',
            'registration_number' => 'required|string|max:20|unique:vehicles',
            'year' => 'nullable|integer|min:1900|max:' . (date('Y') + 1),
            'color' => 'nullable|string|max:50',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorResponse($validator->errors());
        }

        $vehicle = Vehicle::create([
            'user_id' => $request->user()->id,
            ...$request->only(['type', 'make', 'model', 'registration_number', 'year', 'color']),
        ]);

        return $this->successResponse($vehicle, 'Vehicle created successfully', 201);
    }

    /**
     * Display the specified vehicle
     */
    #[OA\Get(
        path: '/api/v1/vehicles/{id}',
        summary: 'Get vehicle details',
        description: 'Retrieve details of a specific vehicle',
        tags: ['Vehicles'],
        security: [['sanctum' => []]],
        parameters: [
            new OA\Parameter(name: 'id', in: 'path', required: true, schema: new OA\Schema(type: 'integer'), example: 1),
        ],
        responses: [
            new OA\Response(
                response: 200,
                description: 'Vehicle retrieved successfully',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: true),
                        new OA\Property(property: 'data', type: 'object'),
                        new OA\Property(property: 'message', type: 'string', example: 'Vehicle retrieved successfully'),
                    ]
                )
            ),
            new OA\Response(
                response: 404,
                description: 'Vehicle not found',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: false),
                        new OA\Property(property: 'message', type: 'string', example: 'Vehicle not found'),
                    ]
                )
            ),
        ]
    )]
    public function show(Request $request, string $id): JsonResponse
    {
        $vehicle = $request->user()->vehicles()->find($id);
        
        if (!$vehicle) {
            return $this->notFoundResponse('Vehicle not found');
        }

        return $this->successResponse($vehicle, 'Vehicle retrieved successfully');
    }

    /**
     * Update the specified vehicle
     */
    #[OA\Put(
        path: '/api/v1/vehicles/{id}',
        summary: 'Update vehicle',
        description: 'Update details of a specific vehicle',
        tags: ['Vehicles'],
        security: [['sanctum' => []]],
        parameters: [
            new OA\Parameter(name: 'id', in: 'path', required: true, schema: new OA\Schema(type: 'integer'), example: 1),
        ],
        requestBody: new OA\RequestBody(
            required: true,
            content: new OA\JsonContent(
                properties: [
                    new OA\Property(property: 'type', type: 'string', nullable: true, enum: ['car', 'van', 'scooter', 'motorbike']),
                    new OA\Property(property: 'make', type: 'string', nullable: true),
                    new OA\Property(property: 'model', type: 'string', nullable: true),
                    new OA\Property(property: 'registration_number', type: 'string', nullable: true),
                    new OA\Property(property: 'year', type: 'integer', nullable: true),
                    new OA\Property(property: 'color', type: 'string', nullable: true),
                    new OA\Property(property: 'is_active', type: 'boolean', nullable: true),
                ]
            )
        ),
        responses: [
            new OA\Response(
                response: 200,
                description: 'Vehicle updated successfully',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: true),
                        new OA\Property(property: 'data', type: 'object'),
                        new OA\Property(property: 'message', type: 'string', example: 'Vehicle updated successfully'),
                    ]
                )
            ),
            new OA\Response(
                response: 404,
                description: 'Vehicle not found',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: false),
                        new OA\Property(property: 'message', type: 'string', example: 'Vehicle not found'),
                    ]
                )
            ),
            new OA\Response(
                response: 422,
                description: 'Validation error',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: false),
                        new OA\Property(property: 'message', type: 'string', example: 'Validation failed'),
                        new OA\Property(property: 'errors', type: 'object'),
                    ]
                )
            ),
        ]
    )]
    public function update(Request $request, string $id): JsonResponse
    {
        $vehicle = $request->user()->vehicles()->find($id);
        
        if (!$vehicle) {
            return $this->notFoundResponse('Vehicle not found');
        }

        $validator = Validator::make($request->all(), [
            'type' => 'sometimes|in:car,van,scooter,motorbike',
            'make' => 'sometimes|string|max:255',
            'model' => 'sometimes|string|max:255',
            'registration_number' => 'sometimes|string|max:20|unique:vehicles,registration_number,' . $id,
            'year' => 'nullable|integer|min:1900|max:' . (date('Y') + 1),
            'color' => 'nullable|string|max:50',
            'is_active' => 'sometimes|boolean',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorResponse($validator->errors());
        }

        $vehicle->update($request->only(['type', 'make', 'model', 'registration_number', 'year', 'color', 'is_active']));

        return $this->successResponse($vehicle, 'Vehicle updated successfully');
    }

    /**
     * Remove the specified vehicle
     */
    #[OA\Delete(
        path: '/api/v1/vehicles/{id}',
        summary: 'Delete vehicle',
        description: 'Delete a specific vehicle',
        tags: ['Vehicles'],
        security: [['sanctum' => []]],
        parameters: [
            new OA\Parameter(name: 'id', in: 'path', required: true, schema: new OA\Schema(type: 'integer'), example: 1),
        ],
        responses: [
            new OA\Response(
                response: 200,
                description: 'Vehicle deleted successfully',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: true),
                        new OA\Property(property: 'message', type: 'string', example: 'Vehicle deleted successfully'),
                    ]
                )
            ),
            new OA\Response(
                response: 404,
                description: 'Vehicle not found',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: false),
                        new OA\Property(property: 'message', type: 'string', example: 'Vehicle not found'),
                    ]
                )
            ),
        ]
    )]
    public function destroy(Request $request, string $id): JsonResponse
    {
        $vehicle = $request->user()->vehicles()->find($id);
        
        if (!$vehicle) {
            return $this->notFoundResponse('Vehicle not found');
        }

        $vehicle->delete();

        return $this->successResponse(null, 'Vehicle deleted successfully');
    }
}
