import sqlite3
from typing import Optional

class Company:
    def __init__(self, db_path="instance/app_database.db"):
        self.db_path = db_path
        self._create_company_table()

    def _create_company_table(self):
        """Create the company table if it doesn't already exist."""
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.cursor()
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS company (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    user_id INTEGER,
                    name TEXT,
                    vat TEXT,
                    register_number TEXT,
                    address TEXT,
                    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                    status TEXT NOT NULL DEFAULT 'active'
                );

            """)
            conn.commit()

    def add_company(self, company):
        try:
            with sqlite3.connect(self.db_path) as conn:
                cursor = conn.cursor()
                cursor.execute("""
                    INSERT INTO company (user_id, name, vat, register_number, address) 
                    VALUES (?, ?, ?, ?, ?)
                """, (
                    company['user_id'], 
                    company['name'], 
                    company['vat'], 
                    company['register_number'], 
                    company['address']
                    )
                )
                conn.commit()
            return True
        except sqlite3.IntegrityError:
           return False  
        
    def get_company(self, user_id):
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.cursor()
            cursor.execute("""
                SELECT * FROM company 
                WHERE user_id = ?
            """, (user_id,))
            row = cursor.fetchone()
            if row:
                return {
                    'id': row[0],
                    'user_id': row[1],
                    'name': row[2],
                    'vat': row[3],
                    'register_number': row[4],
                    'address': row[5],
                    'created_at': row[6],
                    'status': row[7],
                }
            return None
        
    def update_company(self, company):
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.cursor()
            cursor.execute('''
                UPDATE company SET name = ?, vat = ?, register_number = ?, address = ?
                WHERE id = ?
            ''', (company['name'], 
                  company['vat'],
                  company['register_number'],
                  company['address'],
                  company['id']))
            conn.commit()

    def delete(self, id):
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.cursor()
            cursor.execute('''
                DELETE FROM company WHERE id=?;
            ''', (id,))
            conn.commit()

    def deactivate(self, id):
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.cursor()
            cursor.execute('''
                UPDATE company SET status = ?
                WHERE id = ?
            ''', ('inactive', id))
            conn.commit()