from __future__ import annotations

import enum
from datetime import date

from sqlalchemy import Boolean, Date, ForeignKey, Integer, JSON, String, Text
from sqlalchemy.orm import Mapped, mapped_column

from app.db.base import Base, TimestampMixin, UUIDMixin


class ValidationStatus(str, enum.Enum):
    draft = "ENTWURF"
    ready_for_review = "BEREIT_ZUR_PRUEFUNG"
    in_review = "IN_PRUEFUNG"
    approved = "FREIGEGEBEN"
    completed = "ABGESCHLOSSEN"
    cancelled = "STORNIERT"


class Validation(Base, UUIDMixin, TimestampMixin):
    __tablename__ = "validations"

    report_number: Mapped[str] = mapped_column(String(80), unique=True, index=True)
    customer_id: Mapped[str] = mapped_column(ForeignKey("customers.id"), index=True)
    location_id: Mapped[str | None] = mapped_column(ForeignKey("locations.id"), index=True)
    contact_id: Mapped[str | None] = mapped_column(ForeignKey("contacts.id"), index=True, nullable=True)
    device_id: Mapped[str | None] = mapped_column(ForeignKey("devices.id"), index=True)
    validation_type: Mapped[str] = mapped_column(String(120))
    project: Mapped[str | None] = mapped_column(String(180))
    test_location: Mapped[str | None] = mapped_column(String(180))
    examiner_name: Mapped[str | None] = mapped_column(String(180))
    participants: Mapped[str | None] = mapped_column(Text)
    operator_name: Mapped[str | None] = mapped_column(String(180))
    scheduled_on: Mapped[date | None] = mapped_column(Date)
    performed_on: Mapped[date | None] = mapped_column(Date)
    next_validation_on: Mapped[date | None] = mapped_column(Date)
    revalidation_interval_months: Mapped[int] = mapped_column(Integer, default=24)
    next_validation_manually_overridden: Mapped[bool] = mapped_column(Boolean, default=False)
    version: Mapped[int] = mapped_column(Integer, default=1)
    previous_validation_id: Mapped[str | None] = mapped_column(ForeignKey("validations.id"), nullable=True)
    examiner_id: Mapped[str | None] = mapped_column(ForeignKey("users.id"), nullable=True)
    status: Mapped[str] = mapped_column(String(40), default=ValidationStatus.draft.value)
    result: Mapped[str | None] = mapped_column(String(120))
    notes: Mapped[str | None] = mapped_column(Text)
    equipment_ids: Mapped[list[str]] = mapped_column(JSON, default=list)
    environment_conditions: Mapped[dict] = mapped_column(JSON, default=dict)
    documentation_checklist: Mapped[list[dict]] = mapped_column(JSON, default=list)
    performance_checklist: Mapped[list[dict]] = mapped_column(JSON, default=list)
    programs: Mapped[list[dict]] = mapped_column(JSON, default=list)
    loading_patterns: Mapped[list[dict]] = mapped_column(JSON, default=list)
    measurement_data: Mapped[list[dict]] = mapped_column(JSON, default=list)
    drying: Mapped[dict] = mapped_column(JSON, default=dict)
    recommendations: Mapped[list[dict]] = mapped_column(JSON, default=list)
    attachments: Mapped[list[dict]] = mapped_column(JSON, default=list)
