"""
建立 tenant_employees 視圖
整合 tenant_emp_settings 和 tenant_emp_resumes 的資料
"""
import psycopg2

conn = psycopg2.connect(
    host="10.1.0.20",
    port=5433,
    database="hr_portal",
    user="admin",
    password="DC1qaz2wsx"
)
conn.autocommit = False
cur = conn.cursor()

try:
    print("Creating tenant_employees view...")

    # 先刪除舊的視圖 (如果存在)
    cur.execute("DROP VIEW IF EXISTS tenant_employees CASCADE;")

    # 建立視圖整合兩個表
    cur.execute("""
        CREATE VIEW tenant_employees AS
        SELECT
            s.id,
            s.tenant_id,
            s.seq_no,
            s.tenant_emp_code AS employee_id,
            s.tenant_keycloak_user_id AS keycloak_user_id,
            r.english_name AS username_base,
            r.legal_name,
            r.english_name,
            r.mobile AS phone,
            r.mobile,
            s.hire_at AS hire_date,
            s.employment_status AS status,
            s.is_active,
            s.edit_by,
            s.created_at,
            s.updated_at
        FROM tenant_emp_settings s
        INNER JOIN tenant_emp_resumes r ON s.tenant_resume_id = r.id;
    """)

    conn.commit()
    print("SUCCESS: tenant_employees view created")

    # 驗證視圖
    cur.execute("""
        SELECT column_name, data_type
        FROM information_schema.columns
        WHERE table_name = 'tenant_employees'
        ORDER BY ordinal_position;
    """)

    columns = cur.fetchall()
    print("\nView structure:")
    for col in columns:
        print(f"  {col[0]:<25} {col[1]}")

    # 測試查詢
    cur.execute("SELECT COUNT(*) FROM tenant_employees;")
    count = cur.fetchone()[0]
    print(f"\nTotal employees: {count}")

    if count > 0:
        cur.execute("SELECT employee_id, legal_name, english_name, status FROM tenant_employees LIMIT 3;")
        employees = cur.fetchall()
        print("\nSample data:")
        for emp in employees:
            print(f"  {emp[0]:<15} {emp[1]:<20} {emp[2]:<20} {emp[3]}")

except Exception as e:
    conn.rollback()
    print(f"ERROR: {e}")
    import traceback
    traceback.print_exc()
finally:
    cur.close()
    conn.close()
