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

export class ApartmentProvider extends BaseProvider<Apartment> {
	public static instance: ApartmentProvider;

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

	public static get model() {
		return Apartment;
	}

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

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

				// Check for active rooms
				const activeRoomCount = await Room.count({
					where: {
						apartment_id: id,
						deleted_at: null,
					},
					transaction: tx,
				});

				if (activeRoomCount > 0) {
					if (options?.warnOnActiveChildren) {
						console.warn(
							`Deleting apartment ${id} will create ${activeRoomCount} ghost rooms. ` +
								'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 ['building_id', 'code'];
	}
}
