"""
Mail Database - Email Account Operations.
"""

import uuid
from typing import Optional, List, Dict

from .mail_db_pool import get_pool


async def create_email_account(
    user_id: str,
    tenant_id: str,
    email: str,
    display_name: str,
    account_type: str,
    imap_host: str,
    imap_port: int,
    imap_ssl: bool,
    smtp_host: str,
    smtp_port: int,
    smtp_ssl: bool,
    vault_path: str,
) -> Optional[str]:
    """Create a new email account. Returns the account ID."""
    pool = await get_pool()
    if pool is None:
        return None

    account_id = str(uuid.uuid4())
    try:
        async with pool.acquire() as conn:
            await conn.execute(
                """
                INSERT INTO external_email_accounts
                (id, user_id, tenant_id, email, display_name, account_type,
                 imap_host, imap_port, imap_ssl, smtp_host, smtp_port, smtp_ssl, vault_path)
                VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
                """,
                account_id, user_id, tenant_id, email, display_name, account_type,
                imap_host, imap_port, imap_ssl, smtp_host, smtp_port, smtp_ssl, vault_path
            )
        return account_id
    except Exception as e:
        print(f"Failed to create email account: {e}")
        return None


async def get_email_accounts(
    user_id: str,
    tenant_id: Optional[str] = None,
) -> List[Dict]:
    """Get all email accounts for a user."""
    pool = await get_pool()
    if pool is None:
        return []

    try:
        async with pool.acquire() as conn:
            if tenant_id:
                rows = await conn.fetch(
                    """
                    SELECT * FROM external_email_accounts
                    WHERE user_id = $1 AND tenant_id = $2
                    ORDER BY created_at
                    """,
                    user_id, tenant_id
                )
            else:
                rows = await conn.fetch(
                    """
                    SELECT * FROM external_email_accounts
                    WHERE user_id = $1
                    ORDER BY created_at
                    """,
                    user_id
                )
            return [dict(r) for r in rows]
    except Exception as e:
        print(f"Failed to get email accounts: {e}")
        return []


async def get_email_account(account_id: str, user_id: str) -> Optional[Dict]:
    """Get a single email account."""
    pool = await get_pool()
    if pool is None:
        return None

    try:
        async with pool.acquire() as conn:
            row = await conn.fetchrow(
                """
                SELECT * FROM external_email_accounts
                WHERE id = $1 AND user_id = $2
                """,
                account_id, user_id
            )
            return dict(row) if row else None
    except Exception as e:
        print(f"Failed to get email account: {e}")
        return None


async def update_account_status(
    account_id: str,
    status: str,
    sync_error: Optional[str] = None,
    email_count: Optional[int] = None,
    unread_count: Optional[int] = None,
) -> bool:
    """Update account sync status."""
    pool = await get_pool()
    if pool is None:
        return False

    try:
        async with pool.acquire() as conn:
            await conn.execute(
                """
                UPDATE external_email_accounts SET
                    status = $2,
                    sync_error = $3,
                    email_count = COALESCE($4, email_count),
                    unread_count = COALESCE($5, unread_count),
                    last_sync = NOW(),
                    updated_at = NOW()
                WHERE id = $1
                """,
                account_id, status, sync_error, email_count, unread_count
            )
        return True
    except Exception as e:
        print(f"Failed to update account status: {e}")
        return False


async def delete_email_account(account_id: str, user_id: str) -> bool:
    """Delete an email account (cascades to emails)."""
    pool = await get_pool()
    if pool is None:
        return False

    try:
        async with pool.acquire() as conn:
            result = await conn.execute(
                """
                DELETE FROM external_email_accounts
                WHERE id = $1 AND user_id = $2
                """,
                account_id, user_id
            )
            return "DELETE" in result
    except Exception as e:
        print(f"Failed to delete email account: {e}")
        return False
