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

export class BuildingProvider extends BaseProvider<Building> {
	public static instance: BuildingProvider;

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

	public static get model() {
		return Building;
	}

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

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

				// Check for active apartments
				const activeApartmentCount = await Apartment.count({
					where: {
						building_id: id,
						deleted_at: null,
					},
					transaction: tx,
				});

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