import uuid
from typing import Optional
from fastapi import APIRouter, Depends, Query, HTTPException, Request
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.database import get_db
from app.core.security import get_current_user
from app.models.core_models import LoginUsers
from app.modules.dealer_portal.routes import get_current_dealer
from app.modules.notifications import schemas, service

# Router for internal ERP staff users
router = APIRouter()

# Router for external dealer portal users
dealer_router = APIRouter()


# ════════════════════════════════════════════════════════════
# STAFF NOTIFICATIONS (Internal ERP)
# ════════════════════════════════════════════════════════════

@router.get("", response_model=schemas.NotificationListResponse)
async def list_staff_notifications(
    limit: int = Query(30, ge=1, le=100),
    unread_only: bool = Query(False),
    current_user: LoginUsers = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    items, unread_count = await service.get_user_notifications(
        db, current_user.user_id, limit=limit, unread_only=unread_only
    )
    return {
        "notifications": items,
        "unread_count": unread_count
    }


@router.patch("/{notification_id}/read")
async def mark_staff_notification_read(
    notification_id: uuid.UUID,
    current_user: LoginUsers = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    success = await service.mark_notification_as_read(
        db, notification_id, user_id=current_user.user_id
    )
    if not success:
        raise HTTPException(status_code=404, detail="Notification not found")
    return {"status": "success"}


@router.post("/mark-all-read")
async def mark_all_staff_notifications_read(
    current_user: LoginUsers = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    updated = await service.mark_all_notifications_as_read(
        db, user_id=current_user.user_id
    )
    return {"status": "success", "marked_read": updated}


# ════════════════════════════════════════════════════════════
# DEALER NOTIFICATIONS (Dealer Portal)
# ════════════════════════════════════════════════════════════

@dealer_router.get("", response_model=schemas.NotificationListResponse)
async def list_dealer_notifications(
    limit: int = Query(30, ge=1, le=100),
    unread_only: bool = Query(False),
    dealer: dict = Depends(get_current_dealer),
    db: AsyncSession = Depends(get_db)
):
    items, unread_count = await service.get_dealer_notifications(
        db, dealer["dealer_id"], limit=limit, unread_only=unread_only
    )
    return {
        "notifications": items,
        "unread_count": unread_count
    }


@dealer_router.patch("/{notification_id}/read")
async def mark_dealer_notification_read(
    notification_id: uuid.UUID,
    dealer: dict = Depends(get_current_dealer),
    db: AsyncSession = Depends(get_db)
):
    success = await service.mark_notification_as_read(
        db, notification_id, dealer_id=dealer["dealer_id"]
    )
    if not success:
        raise HTTPException(status_code=404, detail="Notification not found")
    return {"status": "success"}


@dealer_router.post("/mark-all-read")
async def mark_all_dealer_notifications_read(
    dealer: dict = Depends(get_current_dealer),
    db: AsyncSession = Depends(get_db)
):
    updated = await service.mark_all_notifications_as_read(
        db, dealer_id=dealer["dealer_id"]
    )
    return {"status": "success", "marked_read": updated}
