<?php

namespace App\Http\Controllers\Api\V1;

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

class KycController extends Controller
{
    use ApiResponse;

    /**
     * Upload KYC document
     */
    #[OA\Post(
        path: '/api/v1/kyc/documents',
        summary: 'Upload KYC document',
        description: 'Upload a KYC verification document (driving licence, V5C, or proof of address)',
        tags: ['KYC'],
        security: [['sanctum' => []]],
        requestBody: new OA\RequestBody(
            required: true,
            content: new OA\MediaType(
                mediaType: 'multipart/form-data',
                schema: new OA\Schema(
                    required: ['document_type', 'file'],
                    properties: [
                        new OA\Property(property: 'document_type', type: 'string', enum: ['driving_licence', 'v5c', 'proof_of_address']),
                        new OA\Property(property: 'file', type: 'string', format: 'binary'),
                    ]
                )
            )
        ),
        responses: [
            new OA\Response(
                response: 201,
                description: 'Document uploaded 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: 'Document uploaded 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 uploadDocument(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'document_type' => 'required|in:driving_licence,v5c,proof_of_address',
            'file' => 'required|file|mimes:pdf,jpg,jpeg,png|max:10240',
        ]);

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

        $file = $request->file('file');
        $path = $file->store('kyc_documents', 'public');

        $document = KycDocument::create([
            'user_id' => $request->user()->id,
            'document_type' => $request->document_type,
            'file_path' => $path,
            'file_name' => $file->getClientOriginalName(),
            'mime_type' => $file->getMimeType(),
            'file_size' => $file->getSize(),
            'verification_status' => 'pending',
        ]);

        return $this->successResponse($document, 'Document uploaded successfully', 201);
    }

    /**
     * Upload selfie for liveness check
     */
    #[OA\Post(
        path: '/api/v1/kyc/selfie',
        summary: 'Upload selfie for liveness check',
        description: 'Upload a selfie photo for KYC liveness verification',
        tags: ['KYC'],
        security: [['sanctum' => []]],
        requestBody: new OA\RequestBody(
            required: true,
            content: new OA\MediaType(
                mediaType: 'multipart/form-data',
                schema: new OA\Schema(
                    required: ['file'],
                    properties: [
                        new OA\Property(property: 'file', type: 'string', format: 'binary'),
                    ]
                )
            )
        ),
        responses: [
            new OA\Response(
                response: 201,
                description: 'Selfie uploaded 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: 'Selfie uploaded 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 uploadSelfie(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'file' => 'required|file|mimes:jpg,jpeg,png|max:5120',
        ]);

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

        $file = $request->file('file');
        $path = $file->store('kyc_documents', 'public');

        $document = KycDocument::create([
            'user_id' => $request->user()->id,
            'document_type' => 'selfie',
            'file_path' => $path,
            'file_name' => $file->getClientOriginalName(),
            'mime_type' => $file->getMimeType(),
            'file_size' => $file->getSize(),
            'verification_status' => 'pending',
        ]);

        // TODO: Integrate with KYC provider for liveness check
        // For now, just mark as pending

        return $this->successResponse($document, 'Selfie uploaded successfully', 201);
    }

    /**
     * Get KYC status
     */
    #[OA\Get(
        path: '/api/v1/kyc/status',
        summary: 'Get KYC status',
        description: 'Retrieve the current KYC verification status and uploaded documents',
        tags: ['KYC'],
        security: [['sanctum' => []]],
        responses: [
            new OA\Response(
                response: 200,
                description: 'KYC status retrieved successfully',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: true),
                        new OA\Property(property: 'data', type: 'object', properties: [
                            new OA\Property(property: 'kyc_status', type: 'string', enum: ['pending', 'verified', 'rejected', 'under_review'], example: 'verified'),
                            new OA\Property(property: 'documents', type: 'array', items: new OA\Items(type: 'object')),
                        ]),
                        new OA\Property(property: 'message', type: 'string', example: 'KYC status retrieved successfully'),
                    ]
                )
            ),
        ]
    )]
    public function status(Request $request): JsonResponse
    {
        $user = $request->user();
        $documents = $user->kycDocuments;

        return $this->successResponse([
            'kyc_status' => $user->kyc_status,
            'documents' => $documents,
        ], 'KYC status retrieved successfully');
    }
}
