import sqlite3
from typing import Optional

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

    def _create_categories_table(self):
        """Create the users 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 categories (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT,
                    image TEXT,
                    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                    status TEXT NOT NULL DEFAULT 'active'
                );

            """)
            conn.commit()

    def add(self, name, image: str) -> bool:
        try:
            with sqlite3.connect(self.db_path) as conn:
                cursor = conn.cursor()
                cursor.execute("""
                    INSERT INTO categories (name, image) 
                    VALUES (?, ?)
                """, (name, image))
                conn.commit()
            return True
        except sqlite3.IntegrityError:
            return False  
        
    def get(self, id):
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.cursor()
            cursor.execute("""
                SELECT * FROM categories 
                WHERE id = ? 
            """, (id,))
            row = cursor.fetchone()
            if row:
                return {
                    "id": row[0], 
                    "name": row[1], 
                    "image": row[2],
                    "created_at": row[3],
                    "status":row[4],
                }
            else:
                return None
            
    def get_categories(self):
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.cursor()
            cursor.execute("""
                SELECT * FROM categories;
            """)
            rows = cursor.fetchall()
            if rows:
                buffer = []
                for row in rows:
                    r = {
                        "id": row[0], 
                        "name": row[1], 
                        "image": row[2],
                        "created_at": row[3],
                        "status":row[4],
                    }
                    buffer.append(r)
                return buffer
            else:
                return []
            
    def update(self, name, image, id):
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.cursor()
            cursor.execute('''
                UPDATE categories SET name = ?, image = ?
                WHERE id = ?
            ''', (name, image, id))
            conn.commit()

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