import sqlite3
from dataclasses import dataclass
import hashlib
from typing import Optional

@dataclass
class DocumentsCategoryModel:
    id: Optional[int] = None
    user_id: Optional[int] = None
    name: Optional[str] = None
    created_at: Optional[str] = None
    access: Optional[str] = None

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

    def _create_audit_table(self):
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.cursor()
            cursor.execute(
                """
                CREATE TABLE IF NOT EXISTS documents_category (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    user_id INTEGER NOT NULL,
                    name TEXT,
                    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                    access TEXT
                );
                """
            )
            conn.commit()

    def new_entry(self, entry:DocumentsCategoryModel):
        """Create a new entry."""
        try:
            with sqlite3.connect(self.db_path) as conn:
                cursor = conn.cursor()
                cursor.execute(
                    """
                    INSERT INTO documents_category (user_id, name, access)
                    VALUES (?, ?, ?)
                    """,
                    (entry.user_id, entry.name, entry.access)
                )
                conn.commit()
                return cursor.lastrowid
        except sqlite3.IntegrityError:
            return None
        
    def get_all_entries(self):
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.cursor()
            cursor.execute("SELECT * FROM documents_category")
            rows = cursor.fetchall()

            return [
                DocumentsCategoryModel(
                    id = row[0],
                    user_id =  row[1],
                    name = row[2],
                    created_at = row[3],
                    access = row[4]
                )
                for row in rows
            ]
        
    def get_entries_by_user_id(self, user_id):
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.cursor()
            cursor.execute("SELECT * FROM documents_category WHERE user_id = ?", (user_id, ))
            rows = cursor.fetchall()

            return [
                DocumentsCategoryModel(
                    id = row[0],
                    user_id =  row[1],
                    name = row[2],
                    created_at = row[3],
                    access = row[4]
                )
                for row in rows
            ]
        
    def get_entry_by_id(self, id):
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.cursor()
            cursor.execute("SELECT * FROM documents_category WHERE id = ?", (id, ))
            row = cursor.fetchone()
            if row:
                return DocumentsCategoryModel(
                    id = row[0],
                    user_id =  row[1],
                    name = row[2],
                    created_at = row[3],
                    access = row[4]
                )
            return None

    def update_entry(self, id, name, access):
        try:
            with sqlite3.connect(self.db_path) as conn:
                cursor = conn.cursor()
                cursor.execute(
                    """
                    UPDATE documents_category 
                    SET name = ?, access = ?
                    WHERE id = ?
                    """,
                    (name, access, id)
                )
                conn.commit()
                return cursor.rowcount
        except sqlite3.Error as e:
            print(f"An error occurred: {e}")
            return 0

    def delete_entry(self, id):
        try:
            with sqlite3.connect(self.db_path) as conn:
                cursor = conn.cursor()
                # SQLite allows direct string comparison for ISO 8601 dates
                cursor.execute(
                    "DELETE FROM documents_category WHERE id = ? ",
                    (id,)
                )
                conn.commit()
                return cursor.rowcount  # Returns the number of deleted rows
        except sqlite3.Error as e:
            print(f"An error occurred: {e}")
            return 0