begin;

create or replace function public.default_rectification_chat_session_model()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
begin
  if new.session_type = 'birth_time_rectification' and new.model_id is null then
    select c.model_id into new.model_id
    from public.model_config_versions v
    join public.model_configs c on c.id = v.config_id
    join public.model_providers p on p.id = v.provider_id
    where v.status = 'published'
      and v.enabled
      and v.is_default
      and p.enabled
    limit 1;
  end if;
  return new;
end
$$;

revoke all on function public.default_rectification_chat_session_model() from public, anon, authenticated;

drop trigger if exists chat_sessions_default_rectification_model on public.chat_sessions;
create trigger chat_sessions_default_rectification_model
before insert or update of session_type, model_id on public.chat_sessions
for each row execute function public.default_rectification_chat_session_model();

with default_model as (
  select c.model_id
  from public.model_config_versions v
  join public.model_configs c on c.id = v.config_id
  join public.model_providers p on p.id = v.provider_id
  where v.status = 'published'
    and v.enabled
    and v.is_default
    and p.enabled
  limit 1
)
update public.chat_sessions s
set model_id = default_model.model_id
from default_model
where s.session_type = 'birth_time_rectification'
  and s.model_id is null;

commit;
