import { BaseProvider } from '#templates/base/provider';
import { Room } from '#models/Room';
import { Bed } from '#models/Bed';
import { GenericError } from '#interfaces/error/generic';

export class RoomProvider extends BaseProvider<Room> {
	public static instance: RoomProvider;

	public static getInstance(): RoomProvider {
		RoomProvider.instance ??= new RoomProvider();
		return RoomProvider.instance;
	}

	public static get model() {
		return Room;
	}

	constructor() {
		super('Room');
	}

	override async delete(
		id: string,
		options?: {
			transaction?: any;
			force?: boolean;
			deleted_by?: string;
			warnOnActiveChildren?: boolean;
		},
	): Promise<string> {
		return this.executeInTransaction(async (tx) => {
			try {
				const room = await Room.findByPk(id, { transaction: tx });
				if (!room) {
					throw new GenericError('NOT_FOUND', { resource: 'Room', id });
				}

				// Check for active beds
				const activeBedCount = await Bed.count({
					where: {
						room_id: id,
						deleted_at: null,
					},
					transaction: tx,
				});

				if (activeBedCount > 0) {
					if (options?.warnOnActiveChildren) {
						console.warn(
							`Deleting room ${id} will create ${activeBedCount} ghost beds. ` +
								'Consider cascading soft delete or using active views.',
						);
					}
				}

				// Call BaseProvider delete with deleted_by
				return super.delete(id, { ...options, transaction: tx });
			} catch (error) {
				await this.logError(error as Error);
				throw error;
			}
		}, options?.transaction);
	}

	protected override getUniqueRestoreConstraints(): string[] {
		return ['apartment_id', 'code'];
	}
}
