# /home/Autopartes/pos/tenant_db.py
"""Tenant DB connection manager. Gets a psycopg2 connection for a specific tenant."""

import psycopg2
from config import MASTER_DB_URL, TENANT_DB_URL_TEMPLATE


def get_master_conn():
    """Get connection to nexus_master DB."""
    return psycopg2.connect(MASTER_DB_URL)


def get_tenant_conn(tenant_id):
    """Get connection to a tenant's DB by looking up db_name in nexus_master."""
    master = get_master_conn()
    cur = master.cursor()
    cur.execute("SELECT db_name FROM tenants WHERE id = %s AND is_active = true", (tenant_id,))
    row = cur.fetchone()
    cur.close()
    master.close()

    if not row:
        raise ValueError(f"Tenant {tenant_id} not found or inactive")

    db_name = row[0]
    return psycopg2.connect(TENANT_DB_URL_TEMPLATE.format(db_name=db_name))


def get_tenant_conn_by_dbname(db_name):
    """Get connection to a tenant DB directly by name."""
    return psycopg2.connect(TENANT_DB_URL_TEMPLATE.format(db_name=db_name))
