-- Drop tables if they exist to allow re-running this migration
DROP TABLE IF EXISTS room_roomtypes;
DROP TABLE IF EXISTS roomtypes;

-- Create roomtypes table with sequential ids
CREATE TABLE roomtypes (
    id SERIAL PRIMARY KEY,
    name CHARACTER VARYING,
    admin_specific BOOLEAN NOT NULL DEFAULT FALSE,
    CONSTRAINT roomtypes_name_key UNIQUE (name)
);

-- Create room_roomtypes junction table
CREATE TABLE room_roomtypes (
    id SERIAL PRIMARY KEY,
    room_id INTEGER NOT NULL,
    roomtype_id INTEGER NOT NULL,

    -- Foreign key constraints with CASCADE DELETE
    CONSTRAINT fk_room_roomtypes_room
        FOREIGN KEY (room_id) REFERENCES rooms(id) ON DELETE CASCADE,
    CONSTRAINT fk_room_roomtypes_roomtype
        FOREIGN KEY (roomtype_id) REFERENCES roomtypes(id) ON DELETE CASCADE,

    -- Ensure unique combination of room and roomtype (prevent duplicates)
    UNIQUE(room_id, roomtype_id)
);

-- Create indexes for better query performance
CREATE INDEX idx_room_roomtypes_room_id ON room_roomtypes(room_id);
CREATE INDEX idx_room_roomtypes_roomtype_id ON room_roomtypes(roomtype_id);

