from datetime import datetime, timezone

from sqlalchemy import (
    Column,
    Date,
    DateTime,
    ForeignKey,
    Integer,
    Numeric,
    String,
    Text,
)
from sqlalchemy.orm import relationship

from .db import Base


class Kunde(Base):
    __tablename__ = "kunden"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, nullable=False)
    historie = Column(Text, default="")
    forderungen = relationship("Forderung", back_populates="kunde")


class Forderung(Base):
    __tablename__ = "forderungen"
    id = Column(Integer, primary_key=True, index=True)
    kunde_id = Column(Integer, ForeignKey("kunden.id"))
    verkaeufer_id = Column(Integer, index=True)
    fahrzeug = Column(String, nullable=True)
    fahrgestellnummer = Column(String, nullable=True)
    rechnungsnummer: Column[str] = Column(String, nullable=False)
    betrag = Column(Numeric(12, 2), nullable=False)
    faelligkeit = Column(Date, nullable=True)
    status = Column(String, default="offen")

    kunde = relationship("Kunde", back_populates="forderungen")
    zahlungen = relationship("Zahlung", back_populates="forderung")
    bemerkungen = relationship("Bemerkung", back_populates="forderung")


class Zahlung(Base):
    __tablename__ = "zahlungen"
    id = Column(Integer, primary_key=True, index=True)
    forderung_id = Column(Integer, ForeignKey("forderungen.id"))
    betrag = Column(Numeric(12, 2), nullable=False)
    datum = Column(Date, nullable=False)

    forderung = relationship("Forderung", back_populates="zahlungen")


class Bemerkung(Base):
    __tablename__ = "bemerkungen"
    id = Column(Integer, primary_key=True, index=True)
    forderung_id = Column(Integer, ForeignKey("forderungen.id"))
    benutzer = Column(String, nullable=False)
    bemerkung = Column(Text, nullable=True)
    wiedervorlage_datum = Column(Date, nullable=True)
    zeitstempel = Column(DateTime, default=datetime.now(timezone.utc))

    forderung = relationship("Forderung", back_populates="bemerkungen")
