<?php

namespace App\Http\Controllers\Api\V1;

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

class WorkProviderController extends Controller
{
    use ApiResponse;

    /**
     * Display a listing of work providers
     */
    #[OA\Get(
        path: '/api/v1/work-providers',
        summary: 'List all work providers',
        description: 'Retrieve all linked work providers for the authenticated user',
        tags: ['Work Providers'],
        security: [['sanctum' => []]],
        responses: [
            new OA\Response(
                response: 200,
                description: 'Work providers 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: 'Work providers retrieved successfully'),
                    ]
                )
            ),
        ]
    )]
    public function index(Request $request): JsonResponse
    {
        $providers = WorkProvider::where('user_id', $request->user()->id)->get();
        return $this->successResponse($providers, 'Work providers retrieved successfully');
    }

    /**
     * Store a newly created work provider
     */
    #[OA\Post(
        path: '/api/v1/work-providers',
        summary: 'Link work provider',
        description: 'Link a work provider account (Uber Eats, Just Eat, Deliveroo, Amazon Flex)',
        tags: ['Work Providers'],
        security: [['sanctum' => []]],
        requestBody: new OA\RequestBody(
            required: true,
            content: new OA\JsonContent(
                required: ['provider', 'provider_user_id'],
                properties: [
                    new OA\Property(property: 'provider', type: 'string', enum: ['uber_eats', 'just_eat', 'deliveroo', 'amazon_flex'], example: 'uber_eats'),
                    new OA\Property(property: 'provider_user_id', type: 'string', example: 'user123'),
                    new OA\Property(property: 'provider_token', type: 'string', nullable: true, example: 'token_here'),
                ]
            )
        ),
        responses: [
            new OA\Response(
                response: 201,
                description: 'Work provider linked 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: 'Work provider linked successfully'),
                    ]
                )
            ),
            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(), [
            'provider' => 'required|in:uber_eats,just_eat,deliveroo,amazon_flex',
            'provider_user_id' => 'required|string|max:255',
            'provider_token' => 'nullable|string',
        ]);

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

        $provider = WorkProvider::create([
            'user_id' => $request->user()->id,
            ...$request->only(['provider', 'provider_user_id', 'provider_token']),
        ]);

        return $this->successResponse($provider, 'Work provider linked successfully', 201);
    }

    /**
     * Display the specified work provider
     */
    #[OA\Get(
        path: '/api/v1/work-providers/{id}',
        summary: 'Get work provider details',
        description: 'Retrieve details of a specific work provider',
        tags: ['Work Providers'],
        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: 'Work provider 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: 'Work provider retrieved successfully'),
                    ]
                )
            ),
            new OA\Response(
                response: 404,
                description: 'Work provider not found',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: false),
                        new OA\Property(property: 'message', type: 'string', example: 'Work provider not found'),
                    ]
                )
            ),
        ]
    )]
    public function show(Request $request, string $id): JsonResponse
    {
        $provider = WorkProvider::where('id', $id)
            ->where('user_id', $request->user()->id)
            ->first();

        if (!$provider) {
            return $this->notFoundResponse('Work provider not found');
        }

        return $this->successResponse($provider, 'Work provider retrieved successfully');
    }

    /**
     * Update the specified work provider
     */
    #[OA\Put(
        path: '/api/v1/work-providers/{id}',
        summary: 'Update work provider',
        description: 'Update work provider settings',
        tags: ['Work Providers'],
        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: 'is_active', type: 'boolean', nullable: true),
                    new OA\Property(property: 'auto_sync_enabled', type: 'boolean', nullable: true),
                    new OA\Property(property: 'provider_token', type: 'string', nullable: true),
                ]
            )
        ),
        responses: [
            new OA\Response(
                response: 200,
                description: 'Work provider 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: 'Work provider updated successfully'),
                    ]
                )
            ),
            new OA\Response(
                response: 404,
                description: 'Work provider not found',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: false),
                        new OA\Property(property: 'message', type: 'string', example: 'Work provider not found'),
                    ]
                )
            ),
        ]
    )]
    public function update(Request $request, string $id): JsonResponse
    {
        $provider = WorkProvider::where('id', $id)
            ->where('user_id', $request->user()->id)
            ->first();

        if (!$provider) {
            return $this->notFoundResponse('Work provider not found');
        }

        $validator = Validator::make($request->all(), [
            'is_active' => 'sometimes|boolean',
            'auto_sync_enabled' => 'sometimes|boolean',
            'provider_token' => 'nullable|string',
        ]);

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

        $provider->update($request->only(['is_active', 'auto_sync_enabled', 'provider_token']));

        return $this->successResponse($provider, 'Work provider updated successfully');
    }

    /**
     * Remove the specified work provider
     */
    #[OA\Delete(
        path: '/api/v1/work-providers/{id}',
        summary: 'Unlink work provider',
        description: 'Unlink and delete a work provider account',
        tags: ['Work Providers'],
        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: 'Work provider unlinked successfully',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: true),
                        new OA\Property(property: 'message', type: 'string', example: 'Work provider unlinked successfully'),
                    ]
                )
            ),
            new OA\Response(
                response: 404,
                description: 'Work provider not found',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: false),
                        new OA\Property(property: 'message', type: 'string', example: 'Work provider not found'),
                    ]
                )
            ),
        ]
    )]
    public function destroy(Request $request, string $id): JsonResponse
    {
        $provider = WorkProvider::where('id', $id)
            ->where('user_id', $request->user()->id)
            ->first();

        if (!$provider) {
            return $this->notFoundResponse('Work provider not found');
        }

        $provider->delete();

        return $this->successResponse(null, 'Work provider unlinked successfully');
    }

    /**
     * Link work provider
     */
    #[OA\Post(
        path: '/api/v1/work-providers/{id}/link',
        summary: 'Activate work provider',
        description: 'Activate a linked work provider',
        tags: ['Work Providers'],
        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: 'Work provider linked 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: 'Work provider linked successfully'),
                    ]
                )
            ),
            new OA\Response(
                response: 404,
                description: 'Work provider not found',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: false),
                        new OA\Property(property: 'message', type: 'string', example: 'Work provider not found'),
                    ]
                )
            ),
        ]
    )]
    public function link(Request $request, string $id): JsonResponse
    {
        $provider = WorkProvider::where('id', $id)
            ->where('user_id', $request->user()->id)
            ->first();

        if (!$provider) {
            return $this->notFoundResponse('Work provider not found');
        }

        $provider->update(['is_active' => true]);

        return $this->successResponse($provider, 'Work provider linked successfully');
    }

    /**
     * Unlink work provider
     */
    #[OA\Post(
        path: '/api/v1/work-providers/{id}/unlink',
        summary: 'Deactivate work provider',
        description: 'Deactivate a linked work provider',
        tags: ['Work Providers'],
        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: 'Work provider unlinked 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: 'Work provider unlinked successfully'),
                    ]
                )
            ),
            new OA\Response(
                response: 404,
                description: 'Work provider not found',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: false),
                        new OA\Property(property: 'message', type: 'string', example: 'Work provider not found'),
                    ]
                )
            ),
        ]
    )]
    public function unlink(Request $request, string $id): JsonResponse
    {
        $provider = WorkProvider::where('id', $id)
            ->where('user_id', $request->user()->id)
            ->first();

        if (!$provider) {
            return $this->notFoundResponse('Work provider not found');
        }

        $provider->update(['is_active' => false]);

        return $this->successResponse($provider, 'Work provider unlinked successfully');
    }
}
