from sqlalchemy import Column, Integer, String, Text, Enum, ForeignKey, DateTime, Boolean, JSON, Numeric
from sqlalchemy.orm import relationship
from datetime import datetime
import enum
from ...shared.config.database import Base

class InspectionType(str, enum.Enum):
    pre_checkin = 'pre_checkin'
    post_checkout = 'post_checkout'
    routine = 'routine'
    maintenance = 'maintenance'
    damage = 'damage'

class InspectionStatus(str, enum.Enum):
    pending = 'pending'
    in_progress = 'in_progress'
    completed = 'completed'
    failed = 'failed'
    cancelled = 'cancelled'

class RoomInspection(Base):
    __tablename__ = 'room_inspections'
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    room_id = Column(Integer, ForeignKey('rooms.id'), nullable=False, index=True)
    booking_id = Column(Integer, ForeignKey('bookings.id'), nullable=True, index=True)
    
    inspection_type = Column(Enum(InspectionType), nullable=False)
    status = Column(Enum(InspectionStatus), nullable=False, default=InspectionStatus.pending)
    
    # Scheduling
    scheduled_at = Column(DateTime, nullable=False, index=True)
    started_at = Column(DateTime, nullable=True)
    completed_at = Column(DateTime, nullable=True)
    
    # Assignment
    inspected_by = Column(Integer, ForeignKey('users.id'), nullable=True)
    created_by = Column(Integer, ForeignKey('users.id'), nullable=True)
    
    # Checklist
    checklist_template_id = Column(Integer, nullable=True)  # Reference to checklist template
    checklist_items = Column(JSON, nullable=False)  # Array of {category: string, item: string, status: string, notes: string, photos: string[]}
    # status can be: 'pass', 'fail', 'needs_attention', 'not_applicable'
    
    # Overall assessment
    overall_score = Column(Numeric(3, 2), nullable=True)  # 0-5 rating
    overall_notes = Column(Text, nullable=True)
    issues_found = Column(JSON, nullable=True)  # Array of {severity: string, description: string, photo: string}
    # severity can be: 'critical', 'major', 'minor', 'cosmetic'
    
    # Photos
    photos = Column(JSON, nullable=True)  # Array of photo URLs
    
    # Follow-up
    requires_followup = Column(Boolean, nullable=False, default=False)
    followup_notes = Column(Text, nullable=True)
    maintenance_request_id = Column(Integer, ForeignKey('room_maintenance.id'), nullable=True)
    
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    
    # Relationships
    room = relationship('Room', back_populates='inspections')
    booking = relationship('Booking')
    inspector = relationship('User', foreign_keys=[inspected_by])
    creator = relationship('User', foreign_keys=[created_by])
    maintenance_request = relationship('RoomMaintenance', foreign_keys=[maintenance_request_id])

