"""Immutable point ledger — Phase 7.2."""
from __future__ import annotations

import uuid
from datetime import datetime

from sqlalchemy import DateTime, Index, Integer, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.types import JSON

from app.core.database import Base
from app.models.base import TenantMixin, UUIDPrimaryKeyMixin
from app.models.types import GUID, LedgerEntryType


class PointLedgerEntry(UUIDPrimaryKeyMixin, TenantMixin, Base):
    """Append-only ledger entry. Balance = SUM(signed amounts). Never update/delete."""

    __tablename__ = "point_ledger_entries"

    point_account_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    program_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    member_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    entry_type: Mapped[LedgerEntryType] = mapped_column(nullable=False)
    # Signed amount: earn/adjust+ positive; redeem/expire/adjust- negative
    amount: Mapped[int] = mapped_column(Integer, nullable=False)
    balance_after: Mapped[int] = mapped_column(Integer, nullable=False)
    idempotency_key: Mapped[str | None] = mapped_column(String(100), nullable=True)
    reference_type: Mapped[str | None] = mapped_column(String(50), nullable=True)
    reference_id: Mapped[str | None] = mapped_column(String(100), nullable=True)
    reason: Mapped[str | None] = mapped_column(String(500), nullable=True)
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    expires_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True
    )
    actor_user_id: Mapped[str | None] = mapped_column(String(100), nullable=True)
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), nullable=False
    )

    __table_args__ = (
        UniqueConstraint(
            "tenant_id",
            "idempotency_key",
            name="uq_point_ledger_tenant_idempotency",
        ),
        Index("ix_point_ledger_account", "tenant_id", "point_account_id"),
        Index("ix_point_ledger_member", "tenant_id", "member_id"),
        Index("ix_point_ledger_type", "tenant_id", "entry_type"),
        Index("ix_point_ledger_created", "tenant_id", "created_at"),
        Index("ix_point_ledger_expires", "tenant_id", "expires_at"),
    )
