# retoor <retoor@molodetz.nl>

from .core import datetime, db, get_table, timezone
from .soft_delete import soft_delete


EMAIL_ACCOUNT_DEFAULTS: dict[str, object] = {
    "imap_host": "",
    "imap_port": 993,
    "imap_ssl": 1,
    "imap_starttls": 0,
    "smtp_host": "",
    "smtp_port": 587,
    "smtp_ssl": 0,
    "smtp_starttls": 1,
    "username": "",
    "password": "",
    "from_address": "",
    "from_name": "",
}


def list_email_accounts(owner_kind: str, owner_id: str) -> list:
    if "email_accounts" not in db.tables:
        return []
    return list(
        db["email_accounts"].find(
            owner_kind=owner_kind, owner_id=owner_id, deleted_at=None
        )
    )


def get_email_account(owner_kind: str, owner_id: str, label: str) -> dict | None:
    if "email_accounts" not in db.tables:
        return None
    return db["email_accounts"].find_one(
        owner_kind=owner_kind, owner_id=owner_id, label=label, deleted_at=None
    )


def set_email_account(
    owner_kind: str, owner_id: str, label: str, fields: dict
) -> dict:
    from devplacepy.utils import generate_uid

    table = get_table("email_accounts")
    now = datetime.now(timezone.utc).isoformat()
    existing = table.find_one(owner_kind=owner_kind, owner_id=owner_id, label=label)
    values = {**EMAIL_ACCOUNT_DEFAULTS, **(existing or {}), **fields}
    if not values.get("from_address"):
        values["from_address"] = values.get("username") or ""
    record = {
        key: values.get(key, default)
        for key, default in EMAIL_ACCOUNT_DEFAULTS.items()
    }
    if existing:
        record.update(
            {
                "id": existing["id"],
                "updated_at": now,
                "deleted_at": None,
                "deleted_by": None,
            }
        )
        table.update(record, ["id"])
        result = {**existing, **record}
    else:
        result = {
            "uid": generate_uid(),
            "owner_kind": owner_kind,
            "owner_id": owner_id,
            "label": label,
            "created_at": now,
            "updated_at": now,
            "deleted_at": None,
            "deleted_by": None,
            **record,
        }
        table.insert(result)
    return result


def delete_email_account(
    owner_kind: str, owner_id: str, label: str, deleted_by: str | None = None
) -> int:
    if "email_accounts" not in db.tables:
        return 0
    count = soft_delete(
        "email_accounts",
        deleted_by or f"{owner_kind}:{owner_id}",
        owner_kind=owner_kind,
        owner_id=owner_id,
        label=label,
    )
    return int(count)
