from dataclasses import dataclass, field
from datetime import UTC, datetime

from dataclasses_ujson.dataclasses_ujson import UJsonMixin  # type: ignore
from sqlalchemy import (
    BigInteger,
    Column,
    DateTime,
    ForeignKeyConstraint,
    String,
)
from sqlalchemy.orm import relationship

from server.config import get_app_config
from server.infra.db.db_mapper import mapper_registry
from server.modules.attachments.repository.attachments import Attachment
from server.modules.descriptions.repository.models import Beerds
from server.modules.rate import domain


@mapper_registry.mapped
@dataclass
class Vote(UJsonMixin):
    __sa_dataclass_metadata_key__ = "sa"
    __tablename__ = "votes"
    __table_args__ = (
        ForeignKeyConstraint(["attachment_id"], ["attachments.id"], "votes_attachment_id_fk"),
        ForeignKeyConstraint(["beerd_id"], ["beerds.id"], "votes_beerd_id_fk"),
    )

    __mapper_args__ = {
        "properties": {
            "beerd": relationship(Beerds, foreign_keys="Vote.beerd_id"),
            "attachment": relationship(Attachment, foreign_keys="Vote.attachment_id"),
        }
    }
    id: str = field(metadata={"sa": Column(String(), primary_key=True, nullable=False)})
    attachment_id: str = field(metadata={"sa": Column(String(), nullable=False)})
    beerd_id: str = field(metadata={"sa": Column(String(), nullable=False)})
    rate: int = field(metadata={"sa": Column(BigInteger(), nullable=False)})
    created_at: datetime = field(
        default=datetime.now(UTC),
        metadata={"sa": Column(DateTime(timezone=True), nullable=False)},
    )

    def __str__(self):
        return f"{get_app_config().app_public_url}/api/v0/attachment/{self.id}.original.ext"

    @staticmethod
    def from_domain(d: domain.Vote) -> "Vote":
        return Vote(
            id=d.id,
            attachment_id=d.attachment_id,
            beerd_id=d.beerd_id,
            rate=d.rate,
            created_at=d.created_at,
        )
