import sqlite3
from typing import Optional

class FidelityCards:
    def __init__(self, db_path="instance/app_database.db"):
        self.db_path = db_path
        self._create_fidelity_cards_table()
    
    def _create_fidelity_cards_table(self):
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.cursor()
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS fidelity_cards (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    card_id TEXT,
                    card_type INTEGER,
                    client_name TEXT,
                    phone_number TEXT,
                    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
                );
            """)
            conn.commit()

    def add_fidelity_card(self, card_id, card_type, client_name, phone_number):
        try:
            with sqlite3.connect(self.db_path) as conn:
                cursor = conn.cursor()
                cursor.execute("""
                    INSERT INTO fidelity_cards (card_id, card_type, client_name, phone_number) 
                    VALUES (?, ?, ?, ?)
                """, (card_id, card_type, client_name, phone_number,))
                conn.commit()
            return True
        except sqlite3.IntegrityError:
            return False

    def get_all_fidelity_cards(self):
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.cursor()
            cursor.execute("""
                SELECT * FROM fidelity_cards 
            """,)
            rows = cursor.fetchall()
            result = []
            if rows:
                for row in rows: 
                    buffer =  {
                        "id": row[0], 
                        "card_id": row[1], 
                        "card_type": row[2],
                        "client_name": row[3],
                        "phone_number": row[4],
                        "created_at": row[5]
                    }
                    result.append(buffer)
                return result
            return []
    
    def get_fidelity_card(self, id):
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.cursor()
            cursor.execute("""
                SELECT * FROM fidelity_cards WHERE id = ?
            """,(id, ))
            row = cursor.fetchone()
            result = []
            if row:
                result = {
                        "id": row[0], 
                        "card_id": row[1], 
                        "card_type": row[2],
                        "client_name": row[3],
                        "phone_number": row[4],
                        "created_at": row[5]
                    }
                return result
            return None
        
    def remove_fidelity_card(self, id):
         with sqlite3.connect(self.db_path) as conn:
            cursor = conn.cursor()
            cursor.execute('''
                DELETE FROM fidelity_cards WHERE id=?;
            ''', (id,))
            conn.commit()

    def update_card(self, id, card_id, card_type, client_name, phone_number):
        try:
            with sqlite3.connect(self.db_path) as conn:
                cursor = conn.cursor()
                cursor.execute("""
                    UPDATE fidelity_cards
                    SET card_id = ?, card_type = ?, client_name = ?, phone_number = ?
                    WHERE id = ?
                """, (card_id, card_type, client_name, phone_number, id))
                conn.commit()
            return True
        except Exception:
            return False