-- Alpenwerk HR — mutation RPCs (Phase 2/3)
--
-- One Postgres function per business mutation from the spec
-- §4.4/§4.5/§4.6/§4.7. Each function runs as SECURITY INVOKER (the caller's own
-- session), so the existing RLS policy on `employees` (hr_admin only) is the
-- real authorization gate; the is_hr_admin() check at the top of each function
-- just produces a clearer error message than a bare RLS violation.
--
-- A single function call is one Postgres transaction: if any statement raises,
-- everything in that call rolls back automatically. Run this whole file in the
-- Supabase SQL Editor after supabase/schema.sql.

alter table employee_history add column if not exists reorg_scenario_id uuid references reorg_scenarios(id);

create or replace function current_actor_name()
returns text language sql stable as $$
  select coalesce(p.full_name, p.email, 'Unbekannt') from profiles p where p.id = auth.uid();
$$;

create or replace function require_hr_admin()
returns void language plpgsql as $$
begin
  if not is_hr_admin() then
    raise exception 'Nicht berechtigt: nur HR-Admin darf diese Aktion ausführen.';
  end if;
end;
$$;

-- Manager derivation (§2's "reports-to" rule), used by every mutation that
-- changes an employee's team/leadership status.
create or replace function resolve_manager_for(p_team_id uuid, p_is_lead boolean, p_division_id uuid)
returns uuid language plpgsql as $$
declare
  v_manager uuid;
begin
  if p_team_id is not null and not p_is_lead then
    select id into v_manager from employees
      where team_id = p_team_id and is_lead = true and status <> 'Ausgetreten' limit 1;
  elsif p_team_id is not null and p_is_lead then
    select id into v_manager from employees
      where division_id = p_division_id and team_id is null and org_level = 1 and status <> 'Ausgetreten' limit 1;
  else
    select id into v_manager from employees where org_level = 0 and status <> 'Ausgetreten' limit 1;
  end if;
  return v_manager;
end;
$$;

create or replace function generate_company_email(p_first_name text, p_last_name text)
returns text language plpgsql as $$
declare
  base text;
  candidate text;
  n int := 1;
  translit text;
begin
  translit := lower(p_first_name || '.' || p_last_name);
  translit := replace(replace(replace(replace(translit, 'ä','ae'), 'ö','oe'), 'ü','ue'), 'ß','ss');
  base := regexp_replace(translit, '[^a-z0-9.]', '', 'g');
  candidate := base || '@test.manner.at';
  while exists (select 1 from employees where email = candidate) loop
    n := n + 1;
    candidate := base || n::text || '@test.manner.at';
  end loop;
  return candidate;
end;
$$;

-- ── Hire (§4.4) ───────────────────────────────────────────────
create or replace function hire_employee(payload jsonb)
returns uuid language plpgsql as $$
declare
  v_id uuid;
  v_team_id uuid;
  v_division_id uuid;
  v_position record;
  v_email text;
  v_manager uuid;
begin
  perform require_hr_admin();

  if payload->>'position_id' is not null then
    select * into v_position from positions where id = (payload->>'position_id')::uuid and status = 'open';
    if not found then
      raise exception 'Position ist nicht mehr offen.';
    end if;
    v_team_id := v_position.team_id;
    v_division_id := v_position.division_id;
  else
    v_team_id := (payload->>'team_id')::uuid;
    select division_id into v_division_id from teams t join departments d on d.id = t.department_id where t.id = v_team_id;
  end if;

  v_manager := resolve_manager_for(v_team_id, false, v_division_id);
  v_email := generate_company_email(payload->>'first_name', payload->>'last_name');

  insert into employees (
    first_name, last_name, gender, birth_date, sv_nummer, nationality, email, phone,
    team_id, division_id, job_title, location_id, manager_id, org_level, is_lead,
    employment_type, weekly_hours, monthly_salary_gross, contract_type, contract_end_date,
    paygrade, source, status, entry_date
  ) values (
    payload->>'first_name', payload->>'last_name', (payload->>'gender')::gender_type,
    (payload->>'birth_date')::date, payload->>'sv_nummer', coalesce(payload->>'nationality', 'Österreich'),
    v_email, payload->>'phone',
    v_team_id, v_division_id, coalesce(payload->>'job_title', v_position.title), (payload->>'location_id')::uuid,
    v_manager, 3, false,
    coalesce((payload->>'employment_type')::employment_type, 'Vollzeit'),
    coalesce((payload->>'weekly_hours')::numeric, 38.5),
    (payload->>'monthly_salary_gross')::numeric,
    coalesce((payload->>'contract_type')::contract_type, 'unbefristet'),
    nullif(payload->>'contract_end_date', '')::date,
    coalesce((payload->>'paygrade')::paygrade_type, 'B'),
    coalesce((payload->>'source')::source_type, 'Extern'),
    case when (payload->>'entry_date')::date > current_date then 'Geplant' else 'Aktiv' end,
    (payload->>'entry_date')::date
  ) returning id into v_id;

  if payload->>'position_id' is not null then
    update positions set status = 'filled', filled_at = now(), filled_by_employee_id = v_id
      where id = (payload->>'position_id')::uuid;
  end if;

  insert into employee_history (employee_id, event_date, event_type, description)
    values (v_id, (payload->>'entry_date')::date, 'Eintritt', 'Eintritt als ' || coalesce(payload->>'job_title', v_position.title));

  insert into audit_log (actor_user_id, actor_name, action, target_label, target_employee_id, details)
    values (auth.uid(), current_actor_name(), 'Neueinstellung', payload->>'first_name' || ' ' || payload->>'last_name', v_id, 'Eintritt am ' || (payload->>'entry_date'));

  return v_id;
end;
$$;

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

  update employees set manager_id = v_manager where manager_id = v_employee_id and status <> 'Ausgetreten';

  update employees set
    status = 'Ausgetreten',
    exit_date = (payload->>'exit_date')::date,
    exit_reason = payload->>'exit_reason'
  where id = v_employee_id;

  insert into employee_history (employee_id, event_date, event_type, description)
    values (v_employee_id, (payload->>'exit_date')::date, 'Austritt',
      'Austritt (' || (payload->>'exit_reason') || ')' || 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(), 'Austritt', v_name, v_employee_id, payload->>'exit_reason');
end;
$$;

-- ── Versetzung (§4.5) ─────────────────────────────────────────
create or replace function transfer_employee(payload jsonb)
returns void language plpgsql as $$
declare
  v_employee_id uuid := (payload->>'employee_id')::uuid;
  v_new_team_id uuid := (payload->>'new_team_id')::uuid;
  v_division_id uuid;
  v_manager uuid;
  v_name text;
  v_is_lead boolean;
begin
  perform require_hr_admin();
  select division_id into v_division_id from teams t join departments d on d.id = t.department_id where t.id = v_new_team_id;
  select is_lead, first_name || ' ' || last_name into v_is_lead, v_name from employees where id = v_employee_id;
  v_manager := resolve_manager_for(v_new_team_id, v_is_lead, v_division_id);

  update employees set
    team_id = v_new_team_id,
    job_title = coalesce(nullif(payload->>'new_title', ''), job_title),
    manager_id = v_manager
  where id = v_employee_id;

  insert into employee_history (employee_id, event_date, event_type, description)
    values (v_employee_id, (payload->>'effective_date')::date, 'Versetzung',
      'Versetzung, wirksam ab ' || (payload->>'effective_date') ||
      case when payload->>'new_title' is not null and payload->>'new_title' <> '' then ', neue Position: ' || (payload->>'new_title') else '' end);

  insert into audit_log (actor_user_id, actor_name, action, target_label, target_employee_id, details)
    values (auth.uid(), current_actor_name(), 'Versetzung', v_name, v_employee_id, 'Wirksam ab ' || (payload->>'effective_date'));
end;
$$;

-- ── Beförderung (§4.5) ────────────────────────────────────────
create or replace function promote_employee(payload jsonb)
returns void language plpgsql as $$
declare
  v_employee_id uuid := (payload->>'employee_id')::uuid;
  v_old_paygrade paygrade_type;
  v_name text;
  v_details text;
begin
  perform require_hr_admin();
  select paygrade, first_name || ' ' || last_name into v_old_paygrade, v_name from employees where id = v_employee_id;

  update employees set
    job_title = payload->>'new_title',
    monthly_salary_gross = (payload->>'new_salary')::numeric,
    paygrade = coalesce((payload->>'new_paygrade')::paygrade_type, paygrade)
  where id = v_employee_id;

  v_details := 'Neue Position: ' || (payload->>'new_title');
  if payload->>'new_paygrade' is not null and (payload->>'new_paygrade')::paygrade_type <> v_old_paygrade then
    v_details := v_details || ', neue Paygrade: ' || (payload->>'new_paygrade');
  end if;

  insert into employee_history (employee_id, event_date, event_type, description)
    values (v_employee_id, (payload->>'effective_date')::date, 'Beförderung', v_details);

  insert into audit_log (actor_user_id, actor_name, action, target_label, target_employee_id, details)
    values (auth.uid(), current_actor_name(), 'Beförderung', v_name, v_employee_id, v_details);
end;
$$;

-- ── Karenz verwalten (§4.5) — adjust return date or record actual return ──
create or replace function adjust_karenz_return(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 karenz_return_date = (payload->>'new_return_date')::date where id = v_employee_id;

  insert into employee_history (employee_id, event_date, event_type, description)
    values (v_employee_id, current_date, 'Karenz',
      'Rückkehrdatum angepasst auf ' || (payload->>'new_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, 'Neues Rückkehrdatum: ' || (payload->>'new_return_date'));
end;
$$;

create or replace function record_karenz_return(payload jsonb)
returns void language plpgsql as $$
declare
  v_employee_id uuid := (payload->>'employee_id')::uuid;
  v_return_date date := (payload->>'return_date')::date;
  v_name text;
  v_team_id uuid;
  v_division_id uuid;
  v_is_lead boolean;
  v_manager uuid;
  v_employment_type employment_type;
  v_weekly_hours numeric;
begin
  perform require_hr_admin();
  select first_name || ' ' || last_name, team_id, division_id, is_lead
    into v_name, v_team_id, v_division_id, v_is_lead
    from employees where id = v_employee_id;

  if payload->>'employment_mode' = 'Vollzeit' then
    v_employment_type := 'Vollzeit'; v_weekly_hours := 38.5;
  elsif payload->>'employment_mode' = 'Teilzeit' then
    v_employment_type := 'Teilzeit'; v_weekly_hours := (payload->>'weekly_hours')::numeric;
  end if;

  if v_return_date <= current_date then
    v_manager := resolve_manager_for(v_team_id, v_is_lead, v_division_id);
    update employees set
      status = 'Aktiv',
      karenz_return_date = null,
      manager_id = v_manager,
      employment_type = coalesce(v_employment_type, employment_type),
      weekly_hours = coalesce(v_weekly_hours, weekly_hours)
    where id = v_employee_id;
  else
    update employees set karenz_return_date = v_return_date,
      employment_type = coalesce(v_employment_type, employment_type),
      weekly_hours = coalesce(v_weekly_hours, weekly_hours)
    where id = v_employee_id;
  end if;

  insert into employee_history (employee_id, event_date, event_type, description)
    values (v_employee_id, v_return_date, 'Rückkehr', 'Wiedereintritt aus Karenz am ' || (payload->>'return_date'));

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

-- ── Daten ändern (§4.5) — diffs person vs. contract fields ────
create or replace function change_employee_data(payload jsonb)
returns void language plpgsql as $$
declare
  v_employee_id uuid := (payload->>'employee_id')::uuid;
  v_old employees%rowtype;
  v_name text;
  v_person_changes text[] := '{}';
  v_contract_changes text[] := '{}';
  v_person jsonb := payload->'person';
  v_contract jsonb := payload->'contract';
begin
  perform require_hr_admin();
  select * into v_old from employees where id = v_employee_id;
  v_name := v_old.first_name || ' ' || v_old.last_name;

  if v_person ? 'first_name' and (v_person->>'first_name') <> v_old.first_name then v_person_changes := v_person_changes || 'Vorname'; end if;
  if v_person ? 'last_name' and (v_person->>'last_name') <> v_old.last_name then v_person_changes := v_person_changes || 'Nachname'; end if;
  if v_person ? 'gender' and (v_person->>'gender') <> v_old.gender::text then v_person_changes := v_person_changes || 'Geschlecht'; end if;
  if v_person ? 'birth_date' and (v_person->>'birth_date')::date <> v_old.birth_date then v_person_changes := v_person_changes || 'Geburtsdatum'; end if;
  if v_person ? 'sv_nummer' and coalesce(v_person->>'sv_nummer','') <> coalesce(v_old.sv_nummer,'') then v_person_changes := v_person_changes || 'SV-Nummer'; end if;
  if v_person ? 'nationality' and (v_person->>'nationality') <> v_old.nationality then v_person_changes := v_person_changes || 'Staatsbürgerschaft'; end if;
  if v_person ? 'address' and coalesce(v_person->>'address','') <> coalesce(v_old.address,'') then v_person_changes := v_person_changes || 'Adresse'; end if;
  if v_person ? 'address_country' and coalesce(v_person->>'address_country','') <> coalesce(v_old.address_country,'') then v_person_changes := v_person_changes || 'Land'; end if;
  if v_person ? 'email' and (v_person->>'email') <> v_old.email then v_person_changes := v_person_changes || 'E-Mail'; end if;
  if v_person ? 'phone' and coalesce(v_person->>'phone','') <> coalesce(v_old.phone,'') then v_person_changes := v_person_changes || 'Telefon'; end if;

  if v_contract ? 'employment_type' and (v_contract->>'employment_type') <> v_old.employment_type::text then v_contract_changes := v_contract_changes || 'Beschäftigungsausmaß'; end if;
  if v_contract ? 'weekly_hours' and (v_contract->>'weekly_hours')::numeric <> v_old.weekly_hours then v_contract_changes := v_contract_changes || 'Wochenstunden'; end if;
  if v_contract ? 'contract_type' and (v_contract->>'contract_type') <> v_old.contract_type::text then v_contract_changes := v_contract_changes || 'Vertragsart'; end if;
  if v_contract ? 'contract_end_date' and coalesce((v_contract->>'contract_end_date')::date::text,'') <> coalesce(v_old.contract_end_date::text,'') then v_contract_changes := v_contract_changes || 'Befristet bis'; end if;

  update employees set
    first_name = coalesce(v_person->>'first_name', first_name),
    last_name = coalesce(v_person->>'last_name', last_name),
    gender = coalesce((v_person->>'gender')::gender_type, gender),
    birth_date = coalesce((v_person->>'birth_date')::date, birth_date),
    sv_nummer = coalesce(v_person->>'sv_nummer', sv_nummer),
    nationality = coalesce(v_person->>'nationality', nationality),
    address = coalesce(v_person->>'address', address),
    address_country = coalesce(v_person->>'address_country', address_country),
    email = coalesce(v_person->>'email', email),
    phone = coalesce(v_person->>'phone', phone),
    employment_type = coalesce((v_contract->>'employment_type')::employment_type, employment_type),
    weekly_hours = coalesce((v_contract->>'weekly_hours')::numeric, weekly_hours),
    contract_type = coalesce((v_contract->>'contract_type')::contract_type, contract_type),
    contract_end_date = case when v_contract ? 'contract_end_date' then nullif(v_contract->>'contract_end_date','')::date else contract_end_date end
  where id = v_employee_id;

  if array_length(v_person_changes, 1) > 0 then
    insert into employee_history (employee_id, event_date, event_type, description)
      values (v_employee_id, current_date, 'Stammdatenänderung', 'Geänderte Felder: ' || array_to_string(v_person_changes, ', '));
    insert into audit_log (actor_user_id, actor_name, action, target_label, target_employee_id, details)
      values (auth.uid(), current_actor_name(), 'Stammdatenänderung', v_name, v_employee_id, array_to_string(v_person_changes, ', '));
  end if;

  if array_length(v_contract_changes, 1) > 0 then
    insert into employee_history (employee_id, event_date, event_type, description)
      values (v_employee_id, current_date, 'Vertragsänderung', 'Geänderte Felder: ' || array_to_string(v_contract_changes, ', '));
    insert into audit_log (actor_user_id, actor_name, action, target_label, target_employee_id, details)
      values (auth.uid(), current_actor_name(), 'Vertragsänderung', v_name, v_employee_id, array_to_string(v_contract_changes, ', '));
  end if;
end;
$$;

-- ── Wiedereinstellung (§4.5) ──────────────────────────────────
create or replace function rehire_employee(payload jsonb)
returns void language plpgsql as $$
declare
  v_employee_id uuid := (payload->>'employee_id')::uuid;
  v_rehire_date date := (payload->>'rehire_date')::date;
  v_team_id uuid;
  v_division_id uuid;
  v_is_lead boolean;
  v_manager uuid;
  v_name text;
begin
  perform require_hr_admin();
  select team_id, division_id, is_lead, first_name || ' ' || last_name
    into v_team_id, v_division_id, v_is_lead, v_name
    from employees where id = v_employee_id;
  v_manager := resolve_manager_for(v_team_id, v_is_lead, v_division_id);

  update employees set
    status = case when v_rehire_date > current_date then 'Geplant' else 'Aktiv' end,
    entry_date = v_rehire_date,
    exit_date = null,
    exit_reason = null,
    manager_id = v_manager
  where id = v_employee_id;

  insert into employee_history (employee_id, event_date, event_type, description)
    values (v_employee_id, v_rehire_date, 'Wiedereintritt', 'Wiedereinstellung zum ' || (payload->>'rehire_date'));

  insert into audit_log (actor_user_id, actor_name, action, target_label, target_employee_id, details)
    values (auth.uid(), current_actor_name(), 'Wiedereinstellung', v_name, v_employee_id, 'Wiedereintritt am ' || (payload->>'rehire_date'));
end;
$$;

-- ── Position ausschreiben (§4.6) ──────────────────────────────
create or replace function create_position(payload jsonb)
returns uuid language plpgsql as $$
declare
  v_id uuid;
  v_superior_id uuid := (payload->>'superior_employee_id')::uuid;
  v_is_lead boolean := coalesce((payload->>'is_lead')::boolean, false);
  v_team_id uuid;
begin
  perform require_hr_admin();

  if v_is_lead then
    v_team_id := (payload->>'team_id')::uuid;
  else
    select team_id into v_team_id from employees where id = v_superior_id;
  end if;

  insert into positions (title, team_id, is_lead, reports_to_employee_id)
    values (payload->>'title', v_team_id, v_is_lead, v_superior_id)
    returning id into v_id;

  insert into audit_log (actor_user_id, actor_name, action, target_label, details)
    values (auth.uid(), current_actor_name(), 'Ausschreibung', payload->>'title', 'Position ausgeschrieben');

  return v_id;
end;
$$;

-- ── Intern besetzen (§4.6) ────────────────────────────────────
create or replace function staff_position_internally(payload jsonb)
returns void language plpgsql as $$
declare
  v_position record;
  v_employee_id uuid := (payload->>'employee_id')::uuid;
  v_manager uuid;
  v_name text;
begin
  perform require_hr_admin();
  select * into v_position from positions where id = (payload->>'position_id')::uuid and status = 'open';
  if not found then
    raise exception 'Position ist nicht mehr offen.';
  end if;
  select first_name || ' ' || last_name into v_name from employees where id = v_employee_id;

  v_manager := resolve_manager_for(v_position.team_id, v_position.is_lead, v_position.division_id);

  update employees set
    team_id = v_position.team_id,
    job_title = v_position.title,
    source = 'Intern',
    is_lead = case when v_position.is_lead then true else is_lead end,
    org_level = case when v_position.is_lead then 2 else org_level end,
    manager_id = v_manager
  where id = v_employee_id;

  if v_position.is_lead then
    update employees set manager_id = v_employee_id
      where team_id = v_position.team_id and id <> v_employee_id and is_lead = false and status <> 'Ausgetreten';
  end if;

  update positions set status = 'filled', filled_at = now(), filled_by_employee_id = v_employee_id
    where id = v_position.id;

  insert into employee_history (employee_id, event_date, event_type, description)
    values (v_employee_id, current_date, 'Versetzung', 'Interne Besetzung: ' || v_position.title);

  insert into audit_log (actor_user_id, actor_name, action, target_label, target_employee_id, details)
    values (auth.uid(), current_actor_name(), 'Interne Besetzung', v_name, v_employee_id, v_position.title);
end;
$$;

-- ── Reorganisation (§4.7) ─────────────────────────────────────
-- payload: { name, effective_date, moves: [{ kind, label, employee_ids: uuid[], target_team_id }] }
create or replace function apply_reorg(payload jsonb)
returns uuid language plpgsql as $$
declare
  v_scenario_id uuid;
  v_move jsonb;
  v_employee_id text;
  v_target_team_id uuid;
  v_division_id uuid;
  v_is_lead boolean;
  v_manager uuid;
  v_snapshot jsonb := '{}'::jsonb;
  v_old record;
  v_total_moves int := 0;
begin
  perform require_hr_admin();

  insert into reorg_scenarios (name, effective_date, created_by, applied, applied_at)
    values (payload->>'name', (payload->>'effective_date')::date, auth.uid(), true, now())
    returning id into v_scenario_id;

  for v_move in select * from jsonb_array_elements(payload->'moves')
  loop
    v_target_team_id := (v_move->>'target_team_id')::uuid;
    select division_id into v_division_id from teams t join departments d on d.id = t.department_id where t.id = v_target_team_id;

    insert into reorg_moves (scenario_id, kind, payload) values (v_scenario_id, v_move->>'kind', v_move);

    for v_employee_id in select jsonb_array_elements_text(v_move->'employee_ids')
    loop
      select * into v_old from employees where id = v_employee_id::uuid;
      v_snapshot := v_snapshot || jsonb_build_object(v_employee_id, jsonb_build_object(
        'team_id', v_old.team_id, 'division_id', v_old.division_id, 'manager_id', v_old.manager_id
      ));

      v_is_lead := v_old.is_lead;
      v_manager := resolve_manager_for(v_target_team_id, v_is_lead, v_division_id);

      update employees set team_id = v_target_team_id, manager_id = v_manager where id = v_employee_id::uuid;

      insert into employee_history (employee_id, event_date, event_type, description, reorg_scenario_id)
        values (v_employee_id::uuid, (payload->>'effective_date')::date, 'Reorganisation',
          'Reorganisation "' || (payload->>'name') || '": neues Team zugewiesen', v_scenario_id);

      v_total_moves := v_total_moves + 1;
    end loop;
  end loop;

  update reorg_scenarios set undo_snapshot = v_snapshot where id = v_scenario_id;

  insert into audit_log (actor_user_id, actor_name, action, target_label, details)
    values (auth.uid(), current_actor_name(), 'Reorganisation', payload->>'name', v_total_moves || ' Mitarbeiter:innen betroffen');

  return v_scenario_id;
end;
$$;

create or replace function undo_reorg(payload jsonb)
returns void language plpgsql as $$
declare
  v_scenario record;
  v_key text;
  v_val jsonb;
begin
  perform require_hr_admin();
  select * into v_scenario from reorg_scenarios where id = (payload->>'scenario_id')::uuid and applied = true;
  if not found or v_scenario.undo_snapshot is null then
    raise exception 'Reorganisation kann nicht rückgängig gemacht werden (kein Snapshot vorhanden).';
  end if;

  for v_key, v_val in select * from jsonb_each(v_scenario.undo_snapshot)
  loop
    update employees set
      team_id = nullif(v_val->>'team_id','')::uuid,
      division_id = (v_val->>'division_id')::uuid,
      manager_id = nullif(v_val->>'manager_id','')::uuid
    where id = v_key::uuid;
  end loop;

  delete from employee_history where reorg_scenario_id = v_scenario.id;
  update reorg_scenarios set applied = false where id = v_scenario.id;

  insert into audit_log (actor_user_id, actor_name, action, target_label, details)
    values (auth.uid(), current_actor_name(), 'Reorganisation rückgängig', v_scenario.name, 'Reorganisation zurückgesetzt');
end;
$$;
