import uuid
from fastapi import HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func

from app.models.sales_models import CustomerMaster
from app.models.dealer_models import DealerPortalAdminActionLog
from app.core.security import hash_password
from app.modules.dealer_portal_admin.schemas import DealerPortalAccessRequest, DealerPortalAccessResponse


async def update_dealer_portal_access(
    db: AsyncSession, admin_id: uuid.UUID, req: DealerPortalAccessRequest, ip: str | None = None,
) -> DealerPortalAccessResponse:
    dealer = await db.get(CustomerMaster, req.dealer_id)
    if not dealer:
        raise HTTPException(status_code=404, detail="Dealer not found")

    dealer.portal_enabled = req.portal_enabled
    if req.allow_chassis_tracking is not None:
        dealer.allow_chassis_tracking = req.allow_chassis_tracking

    if req.portal_username:
        cleaned_username = req.portal_username.strip()
        existing = (await db.execute(
            select(CustomerMaster).where(
                func.lower(func.trim(CustomerMaster.portal_username)) == cleaned_username.lower(),
                CustomerMaster.customer_id != dealer.customer_id,
            )
        )).scalar_one_or_none()
        if existing:
            raise HTTPException(status_code=400, detail="Username already exists")
        dealer.portal_username = cleaned_username

    if req.portal_password:
        dealer.portal_password_hash = hash_password(req.portal_password)

    db.add(DealerPortalAdminActionLog(
        admin_user_id=admin_id, dealer_id=dealer.customer_id, action_type="UPDATE_PORTAL_ACCESS",
        action_details={"enabled": req.portal_enabled, "tracking": req.allow_chassis_tracking, "username": req.portal_username}, ip_address=ip,
    ))
    await db.commit()
    await db.refresh(dealer)

    return DealerPortalAccessResponse(
        dealer_id=dealer.customer_id, portal_enabled=dealer.portal_enabled, allow_chassis_tracking=dealer.allow_chassis_tracking, portal_username=dealer.portal_username,
    )
