import sqlite3
from config import settings


class MetadataStore:
    def __init__(self):
        self.db_path = settings.METADATA_DB_PATH

    def initialize(self):
        conn = sqlite3.connect(self.db_path)
        conn.execute(
            "CREATE TABLE IF NOT EXISTS sync_state ("
            "  key TEXT PRIMARY KEY,"
            "  value TEXT"
            ")"
        )
        conn.commit()
        conn.close()

    def get_last_synced_id(self) -> int:
        conn = sqlite3.connect(self.db_path)
        cur = conn.execute(
            "SELECT value FROM sync_state WHERE key = 'last_synced_id'"
        )
        row = cur.fetchone()
        conn.close()
        return int(row[0]) if row else 0

    def set_last_synced_id(self, issue_id: int):
        conn = sqlite3.connect(self.db_path)
        conn.execute(
            "INSERT OR REPLACE INTO sync_state (key, value) VALUES ('last_synced_id', ?)",
            (str(issue_id),),
        )
        conn.commit()
        conn.close()


metadata_store = MetadataStore()
