from app.models.room import Room
from app.models.table import Table
from app.schemas.room import RoomRead
from app.schemas.table import TableRead


LAYOUT_UNITS_PER_METER = 100


def units_to_meters(units: int) -> float:
    return round(units / LAYOUT_UNITS_PER_METER, 1)


def meters_to_units(meters: float, *, allow_zero: bool = False) -> int:
    scaled = int(round(meters * 10) * 10)
    minimum = 0 if allow_zero else 1
    return max(minimum, scaled)


def serialize_room(room: Room) -> RoomRead:
    return RoomRead(
        id=room.id,
        venue_id=room.venue_id,
        name=room.name,
        width=units_to_meters(room.width),
        height=units_to_meters(room.height),
        counter_name=room.counter_name,
        counter_x=units_to_meters(room.counter_x) if room.counter_x is not None else None,
        counter_y=units_to_meters(room.counter_y) if room.counter_y is not None else None,
        counter_width=units_to_meters(room.counter_width) if room.counter_width is not None else None,
        counter_height=units_to_meters(room.counter_height) if room.counter_height is not None else None,
        counter_visible=room.counter_visible,
        entrance_name=room.entrance_name,
        entrance_x=units_to_meters(room.entrance_x) if room.entrance_x is not None else None,
        entrance_y=units_to_meters(room.entrance_y) if room.entrance_y is not None else None,
        entrance_width=units_to_meters(room.entrance_width) if room.entrance_width is not None else None,
        entrance_height=units_to_meters(room.entrance_height) if room.entrance_height is not None else None,
        entrance_visible=room.entrance_visible,
        background_image_data_url=room.background_image_data_url,
    )


def serialize_table(table: Table) -> TableRead:
    return TableRead(
        id=table.id,
        room_id=table.room_id,
        name=table.name,
        x=units_to_meters(table.x),
        y=units_to_meters(table.y),
        width=units_to_meters(table.width),
        height=units_to_meters(table.height),
        shape=table.shape,
        rotation_degrees=round(table.rotation_degrees, 1),
        min_seats=table.min_seats,
        max_seats=table.max_seats,
        join_group=table.join_group,
        is_active=table.is_active,
    )
