import { Injectable } from '@nestjs/common';
import { DatabaseService } from '../../../infrastructure/database/database.service';
/**
* Organization/location-scoped evidence for effective menu availability rules.
* This is intentionally read-only; active-menu resolution remains the
* canonical runtime decision path.
*/
@Injectable()
export class MenuAvailabilityRuleReadService {
constructor(private readonly database: DatabaseService) {}
async list(input: { organizationId: string; locationId: string; productId?: string; stationId?: string }) {
if (input.productId !== undefined && !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(input.productId)) {
throw new Error('menu.product_id_invalid');
}
if (input.stationId !== undefined && !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(input.stationId)) {
throw new Error('menu.station_id_invalid');
}
return this.database.query(
`select mar.id,mar.product_id,p.name as product_name,
mar.location_id,mar.place_id,mar.operational_unit_id,
mar.station_id,ks.display_name as station_name,
mar.channel,mar.starts_at,mar.ends_at,mar.available,
mar.reason_code,mar.priority,mar.created_at
from menu_availability_rules mar
join products p on p.id=mar.product_id and p.organization_id=mar.organization_id
left join kitchen_stations ks on ks.id=mar.station_id and ks.organization_id=mar.organization_id and ks.location_id=mar.location_id
where mar.organization_id=$1 and mar.location_id=$2
and ($3::uuid is null or mar.product_id=$3)
and ($4::uuid is null or mar.station_id=$4)
order by mar.priority desc,mar.starts_at desc,lower(p.name),mar.id`,
[input.organizationId, input.locationId, input.productId ?? null, input.stationId ?? null],
);
}
}
