-- Migration 035: Backfill caliper lean_mass / fat_mass from nearest weight_log row
-- Date: 2026-04-06

UPDATE caliper_log c
SET
  lean_mass = sub.lean_mass,
  fat_mass = sub.fat_mass
FROM (
  SELECT
    c2.id,
    round((wl.weight::numeric - (wl.weight::numeric * c2.body_fat_pct::numeric / 100.0))::numeric, 2) AS lean_mass,
    round((wl.weight::numeric * c2.body_fat_pct::numeric / 100.0)::numeric, 2) AS fat_mass
  FROM caliper_log c2
  CROSS JOIN LATERAL (
    SELECT w.weight
    FROM weight_log w
    WHERE w.profile_id = c2.profile_id
    ORDER BY abs(w.date - c2.date) ASC
    LIMIT 1
  ) wl
  WHERE c2.body_fat_pct IS NOT NULL
    AND (c2.lean_mass IS NULL OR c2.fat_mass IS NULL)
) sub
WHERE c.id = sub.id;
