-- Addendum to supabase/functions.sql — run after that file.
--
-- The spec's "Karenz verwalten" panel (§4.5) only covers employees already on
-- Karenz (adjust return date / record return). It doesn't specify the fields
-- for *starting* a Karenz period from Aktiv, even though §4.3 clearly shows a
-- "Karenz" button for that case. This fills that gap with a reasonable,
-- minimal form: start date + planned return date + optional note.

create or replace function start_karenz(payload jsonb)
returns void language plpgsql as $$
declare
  v_employee_id uuid := (payload->>'employee_id')::uuid;
  v_name text;
begin
  perform require_hr_admin();
  select first_name || ' ' || last_name into v_name from employees where id = v_employee_id;

  update employees set status = 'Karenz', karenz_return_date = (payload->>'planned_return_date')::date
    where id = v_employee_id;

  insert into employee_history (employee_id, event_date, event_type, description)
    values (v_employee_id, (payload->>'karenz_start_date')::date, 'Karenz',
      'Karenzantritt, geplante Rückkehr am ' || (payload->>'planned_return_date') ||
      case when payload->>'note' is not null and payload->>'note' <> '' then ' — ' || (payload->>'note') else '' end);

  insert into audit_log (actor_user_id, actor_name, action, target_label, target_employee_id, details)
    values (auth.uid(), current_actor_name(), 'Karenz', v_name, v_employee_id, 'Karenzantritt, geplante Rückkehr ' || (payload->>'planned_return_date'));
end;
$$;
