<?php

namespace App\Http\Controllers\Api\V1;

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

class NotificationController extends Controller
{
    use ApiResponse;

    /**
     * Display a listing of notifications
     */
    #[OA\Get(
        path: '/api/v1/notifications',
        summary: 'List all notifications',
        description: 'Retrieve paginated list of all notifications for the authenticated user',
        tags: ['Notifications'],
        security: [['sanctum' => []]],
        responses: [
            new OA\Response(
                response: 200,
                description: 'Notifications 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: 'data', type: 'array', items: new OA\Items(type: 'object')),
                            new OA\Property(property: 'current_page', type: 'integer'),
                            new OA\Property(property: 'total', type: 'integer'),
                        ]),
                        new OA\Property(property: 'message', type: 'string', example: 'Notifications retrieved successfully'),
                    ]
                )
            ),
        ]
    )]
    public function index(Request $request): JsonResponse
    {
        $notifications = Notification::where('user_id', $request->user()->id)
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        return $this->successResponse($notifications, 'Notifications retrieved successfully');
    }

    /**
     * Mark notification as read
     */
    #[OA\Put(
        path: '/api/v1/notifications/{id}/read',
        summary: 'Mark notification as read',
        description: 'Mark a specific notification as read',
        tags: ['Notifications'],
        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: 'Notification marked as read',
                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: 'Notification marked as read'),
                    ]
                )
            ),
            new OA\Response(
                response: 404,
                description: 'Notification not found',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: false),
                        new OA\Property(property: 'message', type: 'string', example: 'Notification not found'),
                    ]
                )
            ),
        ]
    )]
    public function markAsRead(Request $request, string $id): JsonResponse
    {
        $notification = Notification::where('id', $id)
            ->where('user_id', $request->user()->id)
            ->first();

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

        $notification->update([
            'is_read' => true,
            'read_at' => now(),
        ]);

        return $this->successResponse($notification, 'Notification marked as read');
    }

    /**
     * Register FCM token
     */
    #[OA\Post(
        path: '/api/v1/notifications/token',
        summary: 'Register FCM token',
        description: 'Register Firebase Cloud Messaging token for push notifications',
        tags: ['Notifications'],
        security: [['sanctum' => []]],
        requestBody: new OA\RequestBody(
            required: true,
            content: new OA\JsonContent(
                required: ['fcm_token'],
                properties: [
                    new OA\Property(property: 'fcm_token', type: 'string', example: 'fcm_token_here'),
                ]
            )
        ),
        responses: [
            new OA\Response(
                response: 200,
                description: 'FCM token registered successfully',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: true),
                        new OA\Property(property: 'message', type: 'string', example: 'FCM token registered 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 registerToken(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'fcm_token' => 'required|string',
        ]);

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

        // Update or create notification record with token
        Notification::updateOrCreate(
            [
                'user_id' => $request->user()->id,
                'fcm_token' => $request->fcm_token,
            ],
            [
                'type' => 'token_registration',
                'title' => 'Token Registered',
                'body' => 'Push notification token registered successfully',
            ]
        );

        return $this->successResponse(null, 'FCM token registered successfully');
    }

    /**
     * Update notification preferences
     */
    #[OA\Put(
        path: '/api/v1/notifications/preferences',
        summary: 'Update notification preferences',
        description: 'Update user notification preferences',
        tags: ['Notifications'],
        security: [['sanctum' => []]],
        requestBody: new OA\RequestBody(
            required: true,
            content: new OA\JsonContent(
                properties: [
                    new OA\Property(property: 'preferences', type: 'object', example: ['push_enabled' => true, 'email_enabled' => false]),
                ]
            )
        ),
        responses: [
            new OA\Response(
                response: 200,
                description: 'Notification preferences updated successfully',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'success', type: 'boolean', example: true),
                        new OA\Property(property: 'message', type: 'string', example: 'Notification preferences updated successfully'),
                    ]
                )
            ),
        ]
    )]
    public function updatePreferences(Request $request): JsonResponse
    {
        // TODO: Implement notification preferences
        // For now, just return success
        return $this->successResponse(null, 'Notification preferences updated successfully');
    }
}
