"""Persistência vm123_identity_map — Spec 027 data-model."""

from __future__ import annotations

import json
from datetime import datetime, timezone
from typing import Any


def _now() -> str:
    return datetime.now(timezone.utc).isoformat()


def init_schema(conn) -> None:
    conn.executescript(
        """
        CREATE TABLE IF NOT EXISTS vm123_identity_map (
            desk_username TEXT PRIMARY KEY,
            desk_role TEXT NOT NULL,
            foss_staff_id TEXT,
            odoo_uid INTEGER,
            openpanel_username TEXT,
            provision_json TEXT,
            provisioned_at TEXT,
            updated_at TEXT NOT NULL
        );
        """
    )


def get_map(conn, desk_username: str) -> dict[str, Any] | None:
    row = conn.execute(
        "SELECT * FROM vm123_identity_map WHERE desk_username = ?",
        (desk_username.strip().lower(),),
    ).fetchone()
    if not row:
        return None
    out = dict(row)
    if out.get("provision_json"):
        try:
            out["provision"] = json.loads(out["provision_json"])
        except json.JSONDecodeError:
            out["provision"] = {}
    return out


def upsert_map(
    conn,
    *,
    desk_username: str,
    desk_role: str,
    foss_staff_id: str | None = None,
    odoo_uid: int | None = None,
    openpanel_username: str | None = None,
    provision: dict | None = None,
) -> dict[str, Any]:
    user = desk_username.strip().lower()
    now = _now()
    existing = get_map(conn, user)
    prov_json = json.dumps(provision or {}, ensure_ascii=False)
    if existing:
        conn.execute(
            """
            UPDATE vm123_identity_map SET
              desk_role = ?, foss_staff_id = COALESCE(?, foss_staff_id),
              odoo_uid = COALESCE(?, odoo_uid),
              openpanel_username = COALESCE(?, openpanel_username),
              provision_json = ?, updated_at = ?,
              provisioned_at = COALESCE(provisioned_at, ?)
            WHERE desk_username = ?
            """,
            (
                desk_role,
                foss_staff_id,
                odoo_uid,
                openpanel_username,
                prov_json,
                now,
                now,
                user,
            ),
        )
    else:
        conn.execute(
            """
            INSERT INTO vm123_identity_map
            (desk_username, desk_role, foss_staff_id, odoo_uid, openpanel_username,
             provision_json, provisioned_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            """,
            (user, desk_role, foss_staff_id, odoo_uid, openpanel_username, prov_json, now, now),
        )
    conn.commit()
    return get_map(conn, user) or {}
