from datetime import datetime
from database import get_connection, is_postgres

class CompanyUsers:
    def __init__(self):
        self.ph = "%s" if is_postgres() else "?"

    def access_to_dict(self, row):
        access = {
                'id': row[0],
                'company_user_id': row[1],
                'clients': row[2],
                'transporters': row[3],
                'destinations': row[4],
                'orders_in': row[5],
                'orders_out': row[6],
                'report':row[7],
                'created_at': row[8]
            }
        return access
        
    def insert_company_user_access(self, access_data):
        created_at = datetime.now().isoformat()
        with get_connection() as conn:
            cursor = conn.cursor()
            returning = "RETURNING id" if is_postgres() else ""
            query = f"""
                INSERT INTO company_user_access (
                    company_user_id, clients, transporters, destinations, orders_in, orders_out, report, created_at
                ) VALUES ({self.ph}, {self.ph}, {self.ph}, {self.ph}, {self.ph}, {self.ph}, {self.ph}, {self.ph}) {returning}
            """
            cursor.execute(
                query, 
                (
                    access_data['company_user_id'], 
                    access_data['clients'], 
                    access_data['transporters'], 
                    access_data['destinations'], 
                    access_data['orders_in'],
                    access_data['orders_out'],
                    access_data['report'],
                    created_at
                )
            )
            inserted_id = None
            if is_postgres():
                inserted_id = cursor.fetchone()[0]
            else:
                inserted_id = cursor.lastrowid
            if hasattr(conn, "commit"):
                conn.commit()
            return inserted_id
    
    def get_access_by_company_user_id(self, company_user_id):
        with get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute(f"SELECT * FROM company_user_access WHERE company_user_id = {self.ph}", (company_user_id,))
            row = cursor.fetchone()
            return self.access_to_dict(row) if row else None
        
    def update_company_user_access(self, data):
        with get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute(
                f"""
                UPDATE company_user_access
                SET clients = {self.ph}, transporters = {self.ph}, destinations = {self.ph}, orders_in = {self.ph}, orders_out = {self.ph}, report = {self.ph}
                WHERE company_user_id = {self.ph}
                """,
                (
                    data['clients'],
                    data['transporters'],
                    data['destinations'],
                    data['orders_in'],
                    data['orders_out'],
                    data['report'],
                    data['company_user_id']
                )
            )
            if hasattr(conn, "commit"):
                conn.commit()