import psycopg
import logging
from app.core.settings import get_settings

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("migration")

def run_baseline_migrations():
    """
    Tạo cấu trúc Schema Isolation cho kiến trúc Modular Monolith.
    Tương đương với baseline migration của Alembic.
    """
    settings = get_settings()
    conn_str = f"postgresql://{settings.postgres_user}:{settings.postgres_password}@{settings.postgres_host}:{settings.postgres_port}/{settings.postgres_db}"
    
    queries = [
        # 1. Projects
        "CREATE SCHEMA IF NOT EXISTS projects;",
        """CREATE TABLE IF NOT EXISTS projects.projects (
            id UUID PRIMARY KEY, name TEXT NOT NULL, code TEXT NOT NULL, 
            status TEXT NOT NULL, created_at TIMESTAMP WITH TIME ZONE
        );""",
        
        # 2. Financial
        "CREATE SCHEMA IF NOT EXISTS financial;",
        """CREATE TABLE IF NOT EXISTS financial.project_budgets (
            id UUID PRIMARY KEY, project_id UUID NOT NULL, project_code TEXT NOT NULL,
            total_allocated NUMERIC(18, 4) DEFAULT 0, status TEXT, created_at TIMESTAMP WITH TIME ZONE
        );""",
        
        # 3. Banking
        "CREATE SCHEMA IF NOT EXISTS banking;",
        """CREATE TABLE IF NOT EXISTS banking.transactions (
            id UUID PRIMARY KEY, bank_account_no TEXT NOT NULL, amount NUMERIC(18, 4) NOT NULL,
            transaction_date TIMESTAMP WITH TIME ZONE NOT NULL, description TEXT NOT NULL,
            reconciled BOOLEAN DEFAULT FALSE, reconciled_invoice_id UUID, created_at TIMESTAMP WITH TIME ZONE
        );""",
        
        # 4. Invoices
        "CREATE SCHEMA IF NOT EXISTS invoices;",
        """CREATE TABLE IF NOT EXISTS invoices.invoices (
            id UUID PRIMARY KEY, invoice_no TEXT NOT NULL, supplier_tax_code TEXT NOT NULL,
            total_amount NUMERIC(18, 4) NOT NULL, tax_amount NUMERIC(18, 4) NOT NULL,
            issue_date DATE NOT NULL, status TEXT NOT NULL, project_id UUID, created_at TIMESTAMP WITH TIME ZONE
        );""",
        
        # 5. Partners
        "CREATE SCHEMA IF NOT EXISTS partners;",
        """CREATE TABLE IF NOT EXISTS partners.partners (
            id UUID PRIMARY KEY, name TEXT NOT NULL, tax_code TEXT, type TEXT NOT NULL,
            address TEXT, created_at TIMESTAMP WITH TIME ZONE
        );""",
        
        # 6. Inventory
        "CREATE SCHEMA IF NOT EXISTS inventory;",
        """CREATE TABLE IF NOT EXISTS inventory.items (
            id UUID PRIMARY KEY, material_code TEXT NOT NULL, warehouse_id TEXT NOT NULL,
            quantity_on_hand NUMERIC(18, 4) NOT NULL, reserved_quantity NUMERIC(18, 4) NOT NULL,
            version INTEGER DEFAULT 1
        );"""
    ]
    
    try:
        with psycopg.connect(conn_str) as conn:
            with conn.cursor() as cur:
                for q in queries:
                    cur.execute(q)
            conn.commit()
            logger.info("Baseline Migration hoàn tất thành công!")
    except Exception as e:
        logger.error(f"Lỗi Migration: {e}")

if __name__ == "__main__":
    run_baseline_migrations()
