package com.eu.habbo.messages.incoming.housekeeping;

import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.permissions.Permission;
import com.eu.habbo.habbohotel.rooms.Room;
import com.eu.habbo.messages.incoming.MessageHandler;
import com.eu.habbo.messages.outgoing.housekeeping.HousekeepingActionResultComposer;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Permanently delete a room. Mirrors the minimum-viable subset of
 * RequestDeleteRoomEvent: eject all users from the live room, dispose
 * + uncache, then DELETE FROM rooms. Pets/guild/custom-layout cleanup
 * is intentionally skipped on this slice — leftover rows in those
 * tables become orphans but don't crash the emulator; a follow-up
 * pass can cascade once we have a HK audit-log row to attach the
 * orphan-cleanup to.
 */
public class HousekeepingDeleteRoomEvent extends MessageHandler {
    private static final String ACTION_KEY = "room.delete";

    @Override
    public int getRatelimit() {
        return 2000;
    }

    @Override
    public void handle() throws Exception {
        if (!this.client.getHabbo().hasPermission(Permission.ACC_HOUSEKEEPING)) {
            return;
        }

        int roomId = this.packet.readInt();

        if (roomId <= 0) {
            this.client.sendResponse(new HousekeepingActionResultComposer(ACTION_KEY, false, 0, "housekeeping.error.invalid_input"));
            return;
        }

        Room room = Emulator.getGameEnvironment().getRoomManager().loadRoom(roomId, false);

        if (room != null) {
            room.ejectAll();
            room.preventUnloading = false;
            room.dispose();
            Emulator.getGameEnvironment().getRoomManager().uncacheRoom(room);
        }

        try (Connection connection = Emulator.getDatabase().getDataSource().getConnection();
             PreparedStatement statement = connection.prepareStatement("DELETE FROM rooms WHERE id = ? LIMIT 1")) {
            statement.setInt(1, roomId);
            int rows = statement.executeUpdate();

            if (rows == 0) {
                this.client.sendResponse(new HousekeepingActionResultComposer(ACTION_KEY, false, 0, "housekeeping.error.room_not_found"));
                return;
            }
        } catch (SQLException e) {
            this.client.sendResponse(new HousekeepingActionResultComposer(ACTION_KEY, false, 0, "housekeeping.error.db_failed"));
            return;
        }

        this.client.sendResponse(new HousekeepingActionResultComposer(ACTION_KEY, true, roomId, ""));
    }
}
