"""Gmail account management endpoints."""
import secrets
from datetime import datetime, timezone

from fastapi import APIRouter, Depends, File, HTTPException, Request, UploadFile
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_current_user, get_current_user_csrf, get_db, require_csrf
from app.core.security import log_audit
from app.models import GmailAccount, OAuthClientConfig, OAuthToken, User
from app.services import gmail_service

router = APIRouter(prefix="/gmail", tags=["gmail-accounts"])


class AccountUpdate(BaseModel):
    sending_method: str = "api"     # api | smtp
    daily_limit: int = 200
    campaign_limit: int = 200


def _account_out(account: GmailAccount) -> dict:
    t = account.oauth_token
    return {
        "id": account.id,
        "email": account.email,
        "display_name": account.display_name,
        "status": account.status,
        "sending_method": account.sending_method,
        "daily_limit": account.daily_limit,
        "campaign_limit": account.campaign_limit,
        "sends_today": account.sends_today,
        "last_success_at": account.last_success_at.isoformat() if account.last_success_at else None,
        "error_count": account.error_count,
        "last_error": (account.last_error or "")[:300],
        "cooldown_until": account.cooldown_until.isoformat() if account.cooldown_until else None,
        "has_refresh_token": bool(t and t.refresh_token_enc),
        "token_expires_at": t.expires_at.isoformat() if t and t.expires_at else None,
        "authorized": account.status == "authorized",
    }


@router.get("/accounts")
async def list_accounts(user: User = Depends(get_current_user),
                        db: AsyncSession = Depends(get_db)):
    rows = (await db.execute(select(GmailAccount).where(
        GmailAccount.user_id == user.id).order_by(GmailAccount.id))).scalars().all()
    return {"accounts": [_account_out(a) for a in rows], "count": len(rows)}


@router.post("/accounts/connect")
async def connect_start(user: User = Depends(get_current_user_csrf),
                        db: AsyncSession = Depends(get_db)):
    """Return the Google authorization URL for this user to open (real OAuth start).
    Uses the user's most recently imported client config when available."""
    from sqlalchemy import select as _select

    cfg_row = (await db.execute(
        _select(OAuthClientConfig)
        .where(OAuthClientConfig.user_id == user.id, OAuthClientConfig.is_active == True)  # noqa
        .order_by(OAuthClientConfig.id.desc()))).scalars().first()
    if cfg_row is not None:
        client = gmail_service.resolve_client_config(cfg_row)
    else:
        try:
            client = gmail_service.resolve_client_config()
        except gmail_service.GmailOauthError:
            raise HTTPException(400, "No Google OAuth client configuration imported yet. "
