import { db } from '../db/db_index' import { regions, regionBounds, regionBoundSettings } from '../db/schema' import { and, eq, sql } from 'drizzle-orm' import type { RegionSummary, RegionWithBounds, RegionBoundDto, CreateRegionInput, UpdateRegionInput, CreateRegionBoundInput, UpdateRegionBoundInput, EffectiveRegionSettings, } from '@packages/shared' // Bounds are ordered by numeric priority ascending (lower number = higher precedence). const priorityOrder = sql`CAST(${regionBounds.priority} AS REAL) ASC` function toSummary(region: typeof regions.$inferSelect): RegionSummary { return { id: region.id, name: region.name, description: region.description } } function toBoundDto(bound: typeof regionBounds.$inferSelect): RegionBoundDto { return { id: bound.id, regionId: bound.regionId, description: bound.description, geojson: bound.geojson as RegionBoundDto['geojson'], priority: bound.priority ?? '', } } export async function getAllRegions(): Promise { const rows = await db.select().from(regions).orderBy(regions.name) return rows.map(toSummary) } export async function getRegionById(id: number): Promise { const row = await db.query.regions.findFirst({ where: eq(regions.id, id) }) return row ? toSummary(row) : null } export async function getRegionWithBounds(id: number): Promise { const region = await db.query.regions.findFirst({ where: eq(regions.id, id) }) if (!region) return null const bounds = await db .select() .from(regionBounds) .where(eq(regionBounds.regionId, id)) .orderBy(priorityOrder) return { ...toSummary(region), bounds: bounds.map(toBoundDto) } } export async function createRegion(input: CreateRegionInput): Promise { const [row] = await db .insert(regions) .values({ name: input.name, description: input.description ?? null }) .returning() return toSummary(row) } export async function updateRegion(input: UpdateRegionInput): Promise { const [row] = await db .update(regions) .set({ ...(input.name !== undefined ? { name: input.name } : {}), ...(input.description !== undefined ? { description: input.description } : {}), }) .where(eq(regions.id, input.id)) .returning() return row ? toSummary(row) : null } export async function getBoundsForRegion(regionId: number): Promise { const rows = await db .select() .from(regionBounds) .where(eq(regionBounds.regionId, regionId)) .orderBy(priorityOrder) return rows.map(toBoundDto) } export async function getBoundById(id: number): Promise { const row = await db.query.regionBounds.findFirst({ where: eq(regionBounds.id, id) }) return row ? toBoundDto(row) : null } export async function createRegionBound(input: CreateRegionBoundInput): Promise { const [row] = await db .insert(regionBounds) .values({ regionId: input.regionId, description: input.description ?? null, geojson: input.geojson, priority: String(input.priority), }) .returning() return toBoundDto(row) } export async function updateRegionBound(input: UpdateRegionBoundInput): Promise { const [row] = await db .update(regionBounds) .set({ ...(input.description !== undefined ? { description: input.description } : {}), ...(input.geojson !== undefined ? { geojson: input.geojson } : {}), ...(input.priority !== undefined ? { priority: String(input.priority) } : {}), }) .where(eq(regionBounds.id, input.id)) .returning() return row ? toBoundDto(row) : null } export async function getBoundSettings(boundId: number): Promise> { const rows = await db .select() .from(regionBoundSettings) .where(eq(regionBoundSettings.boundId, boundId)) const result: Record = {} for (const row of rows) result[row.key] = row.value return result } export async function upsertBoundSettings( boundId: number, settings: Array<{ key: string; value: string | null }> ): Promise { const bound = await db.query.regionBounds.findFirst({ where: eq(regionBounds.id, boundId), columns: { id: true, regionId: true }, }) if (!bound) throw new Error(`Region bound ${boundId} not found`) await db.transaction(async (tx) => { for (const { key, value } of settings) { const existing = await tx.query.regionBoundSettings.findFirst({ where: and( eq(regionBoundSettings.boundId, boundId), eq(regionBoundSettings.key, key) ), columns: { id: true }, }) if (existing) { await tx .update(regionBoundSettings) .set({ value: value === null ? null : String(value) }) .where(eq(regionBoundSettings.id, existing.id)) } else { await tx.insert(regionBoundSettings).values({ regionId: bound.regionId, boundId, key, value: value === null ? null : String(value), }) } } }) } /** Effective region settings = settings of the region's lowest-numbered-priority bound. */ export async function getEffectiveRegionSettings(regionId: number): Promise { const bound = await db.query.regionBounds.findFirst({ where: eq(regionBounds.regionId, regionId), orderBy: priorityOrder, }) if (!bound) return null const settings = await getBoundSettings(bound.id) return { regionId, boundId: bound.id, priority: bound.priority ?? '', settings, } }