import psycopg
import psycopg.conninfo
from psycopg.rows import class_row
from src.__types.errors import PriceCodeNotFoundError
from src.__types.index import Price
from src.settings import Settings

settings = Settings()


class PriceRepository:
    """価格を管理するリポジトリ"""

    def __init__(self, connection: psycopg.Connection) -> None:
        self.connection = connection

    def get(self, code: str) -> Price:
        """指定されたコードの価格を取得する"""
        with self.connection.cursor(row_factory=class_row(Price)) as cur:
            cur.execute(
                "SELECT code, price FROM prices WHERE code = %(code)s",
                {
                    "code": code,
                },
            )
            if price := cur.fetchone():
                return price

            raise PriceCodeNotFoundError(f"Not found code: {code}")
