alter table public.assessments
  add column if not exists is_finalized boolean not null default false,
  add column if not exists finalized_at timestamptz,
  add column if not exists finalization_reminder_sent_at timestamptz;

create index if not exists idx_assessments_user_id_finalization
on public.assessments (user_id, is_finalized, created_at desc);

create index if not exists idx_assessments_open_finalization_reminders
on public.assessments (created_at)
where is_finalized = false and finalization_reminder_sent_at is null;

create or replace function public.guard_assessment_finalization()
returns trigger as $$
begin
  if tg_op = 'UPDATE' and old.is_finalized then
    if new.pat_type is distinct from old.pat_type
      or new.datum is distinct from old.datum
      or new.name is distinct from old.name
      or new.exercises is distinct from old.exercises
      or new.is_finalized is distinct from old.is_finalized
      or new.finalized_at is distinct from old.finalized_at then
      raise exception 'Finalisierte Bewertungen koennen nicht mehr geaendert werden.';
    end if;
  end if;

  if new.is_finalized then
    if tg_op = 'INSERT' then
      new.finalized_at := coalesce(new.finalized_at, now());
    else
      new.finalized_at := coalesce(new.finalized_at, old.finalized_at, now());
    end if;
    new.finalization_reminder_sent_at := null;
  else
    new.finalized_at := null;
  end if;

  return new;
end;
$$ language plpgsql;

drop trigger if exists trg_assessments_finalization_guard on public.assessments;
create trigger trg_assessments_finalization_guard
before insert or update on public.assessments
for each row execute function public.guard_assessment_finalization();
