import os
from typing import List, Optional

from dotenv import load_dotenv
from sqlalchemy import ForeignKey, String, create_engine, Table
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship, Session
from sqlalchemy import MetaData

metadata_obj = MetaData()

load_dotenv()

DB_PASS = os.getenv("DOCKER_POSTGRES_PASS")

# Create engine for connecting to postgres test db
engine = create_engine(
    f'postgresql+psycopg2://postgres:{DB_PASS}@localhost:5432/postgres')


class Base(DeclarativeBase):
    pass

class User(Base):
    __tablename__ = "user_account"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(30))
    fullname: Mapped[Optional[str]]
    addresses: Mapped[List["Address"]] = relationship(back_populates="user")
    def __repr__(self) -> str:
        return f"User(id={self.id!r}, name={self.name!r}, fullname={self.fullname!r})"

class Address(Base):
    __tablename__ = "address"
    id: Mapped[int] = mapped_column(primary_key=True)
    email_address: Mapped[str]
    user_id = mapped_column(ForeignKey("user_account.id"))
    user: Mapped[User] = relationship(back_populates="addresses")
    def __repr__(self) -> str:
        return f"Address(id={self.id!r}, email_address={self.email_address!r})"

# Base.metadata.create_all(engine)
# user_table = Table("user_account", metadata_obj, autoload_with=engine)
# address_table = Table("address", metadata_obj, autoload_with=engine)
# user_table

krabs = User(name="ehkrabs", fullname="Mister krabs")

session = Session(engine)
session.add(krabs)
print(session.new)
session.flush()