from sqlalchemy import (
    Column,
    Integer,
    String,
    JSON,
    TIMESTAMP,
    func,
    UniqueConstraint,
)
from backend.app.db.base import Base


class PostcodeSearch(Base):
    __tablename__ = "postcode_search"

    id = Column(Integer, primary_key=True, autoincrement=True)

    # Normalized postcode (uppercase, no spaces)
    postcode = Column(String, nullable=False, unique=True)

    # Full OS Places API response (stored as JSONB)
    result_data = Column(JSON, nullable=False)

    # Timestamp for when the entry was first created
    created_at = Column(TIMESTAMP(timezone=False), server_default=func.now(), nullable=False)

    __table_args__ = (
        UniqueConstraint("postcode", name="uq_postcode_search_postcode"),
    )

    def __repr__(self):
        return f"<PostcodeSearch(id={self.id}, postcode='{self.postcode}')>"
