import { adapters, migrationFields, newUuid } from '@/services/serviceConfig';
import { auditService } from '@/services/auditService';
export const measurementService = {
  sessions: () => adapters.database.list('MeasurementSession'),
  session: async (uuid) => (await adapters.database.filter('MeasurementSession', { uuid }, '-updated_date', 1))[0],
  definitions: (workflow) => adapters.database.filter('MeasurementDefinition', { workflow, active: true }, 'sequence'),
  values: (session_uuid) => adapters.database.filter('MeasurementValue', { session_uuid }),
  async save(session, definition, data, actor) { const existing = (await adapters.database.filter('MeasurementValue', { session_uuid: session.uuid, definition_uuid: definition.uuid }, '-updated_date', 1))[0]; const previous = (await adapters.database.filter('MeasurementValue', { definition_uuid: definition.uuid }, '-measured_date', 20)).find(v => v.session_uuid !== session.uuid && v.value_mm); const value_mm = data.entered_unit === 'cm' ? Number(data.value) * 10 : Number(data.value); const warnings = []; if (definition.unit === 'mm' && (value_mm < definition.minimum_value || value_mm > definition.maximum_value)) warnings.push(`Outside expected range ${definition.minimum_value}–${definition.maximum_value} mm.`); if (data.entered_unit === 'mm' && value_mm < definition.minimum_value && value_mm * 10 <= definition.maximum_value) warnings.push('Likely wrong unit: this value may have been entered in centimetres.'); if (previous && Math.abs(value_mm - previous.value_mm) / previous.value_mm > 0.2) warnings.push(`More than 20% different from a previous ${definition.name} record.`); const warning = warnings.length ? `${warnings.join(' ')} Manual review required.` : ''; const payload = { value_mm, entered_unit: data.entered_unit, confidence: data.confidence, measured_by: actor, measured_date: new Date().toISOString().slice(0,10), notes: data.notes, photo_url: data.photo_url || '', storage_destination: data.storage_destination || '', warning, updated_by_name: actor }; const saved = existing ? await adapters.database.update('MeasurementValue', existing.id, payload) : await adapters.database.create('MeasurementValue', { ...payload, uuid: newUuid('measure'), session_uuid: session.uuid, definition_uuid: definition.uuid, project_uuid: session.project_uuid, ...migrationFields(actor) }); await auditService.record('measurement_changed', 'MeasurementValue', saved.uuid, `Saved ${definition.name}`, actor, warning); return saved; },
  async skip(session, definition, reason, actor) { const saved = await adapters.database.create('MeasurementValue', { uuid: newUuid('measure'), session_uuid: session.uuid, definition_uuid: definition.uuid, project_uuid: session.project_uuid, entered_unit: 'text', skip_reason: reason, measured_by: actor, measured_date: new Date().toISOString().slice(0,10), ...migrationFields(actor) }); await auditService.record('measurement_skipped', 'MeasurementValue', saved.uuid, `Skipped ${definition.name}: ${reason}`, actor); return saved; },
  progress: (session, complete, total) => adapters.database.update('MeasurementSession', session.id, { progress_percent: Math.round((complete / total) * 100), status: complete >= total ? 'Complete' : 'In progress' }),
  pause: (session) => adapters.database.update('MeasurementSession', session.id, { status: 'Paused' }),
};