from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy.dialects.mysql import insert
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_db, get_tenant_by_appid_or_domain as get_tenant_by_domain
from app.core.models.newsletter_subscription import NewsletterSubscription


router = APIRouter(prefix="/store/newsletter", tags=["Store newsletter"])


def normalize_email(email: str) -> str:
    return email.strip().lower()


class SubscribeIn(BaseModel):
    email: str


@router.post("/subscribe", summary="Subscribe to newsletter")
async def subscribe(
    body: SubscribeIn,
    tid: int = Depends(get_tenant_by_domain),
    db: AsyncSession = Depends(get_db),
):
    email = normalize_email(body.email)
    if not email or "@" not in email or email.startswith("@") or email.endswith("@"):
        raise HTTPException(status_code=422, detail="Please enter a valid email address")

    await db.execute(
        insert(NewsletterSubscription)
        .values(tenant_id=tid, email=email)
        .prefix_with("IGNORE")
    )
    await db.commit()
    return {"subscribed": True}
