-- 1. Move "base hourly rate" off team_members.hourly_rate_usd (which was
--    Adi's rate as a proxy) and onto organizations.default_hourly_rate_usd.
-- 2. Back-compute time_entries.duration_seconds for backfilled rows where
--    we only stored the converted value. Computed as
--    converted_duration_seconds / team_member.rate_proportion. Only fills
--    rows that currently have NULL.

alter table public.organizations
  add column if not exists default_hourly_rate_usd numeric(8, 2);

-- Seed the base rate from whatever was on Adi's team_members row.
update public.organizations o
set default_hourly_rate_usd = coalesce(
  (
    select hourly_rate_usd
    from public.team_members
    where org_id = o.id and email = 'info@adipramono.com'
  ),
  14.00
)
where default_hourly_rate_usd is null;

-- Back-compute source duration for backfilled rows. Skips rows without a
-- matched team member or a zero proportion (would divide by zero).
update public.time_entries te
set duration_seconds = round(
  te.converted_duration_seconds::numeric / tm.rate_proportion
)::int
from public.team_members tm
where te.team_member_id = tm.id
  and te.duration_seconds is null
  and te.converted_duration_seconds is not null
  and tm.rate_proportion > 0;
