from ..models import DbBaseModel
from ..utils import create_configured_db_engine, create_pydantic_record
from pydantic import BaseModel
from sqlalchemy import text
from fastapi import HTTPException
from crud_start import DB_NAME

def get_record_with_filters(record_class: BaseModel, filters: dict) -> list[DbBaseModel]:
    """Select records from the database table corresponding to the given record_class
    applying the given filters.

    Parameters
    ----------
    record_class: BaseModel :
        The Pydantic model class corresponding to the database table.
    filters: dict :
        A dictionary of filters to apply to the query.

    Returns
    -------
    list[DbBaseModel] :
        A list of database records matching the filters.
    """
    conn = create_configured_db_engine(DB_NAME)
    table_name = record_class.__name__.lower() + "s"  # pluralize

    query = f"SELECT * FROM {table_name} WHERE "
    query += " AND ".join([f"{key} = {value}" for key, value in filters.items()])
    result = conn.execute(text(query))
    rows = result.fetchall()
    conn.close()
    records = []
    for row in rows:
        records.append(create_pydantic_record(record_class, row))
    if records:
        return records
    else:
        raise HTTPException(status_code=404, detail="Not found record with given filters")
    
def get_all_records(record_class: BaseModel) -> list[DbBaseModel]:
    """Select all records from the database table corresponding to the given record_class.

    Parameters
    ----------
    record_class: BaseModel :
        The Pydantic model class corresponding to the database table.

    Returns
    -------
    list[DbBaseModel] :
        A list of all database records.
    """
    conn = create_configured_db_engine(DB_NAME)
    table_name = record_class.__name__.lower() + "s"  # pluralize
    query_select = text(f"SELECT * FROM {table_name}")
    result = conn.execute(query_select)
    rows = result.fetchall()
    conn.close()
    records = []
    for row in rows:
        records.append(create_pydantic_record(record_class, row))
    return records
