-- Angehörige add/remove now take a "Wirksam ab" like every other mutation
-- in Daten ändern — a future-dated add/remove is queued the same way
-- transfer/promotion/contract changes already are (see
-- 20260714120050_pending_org_changes.sql) and picked up by the existing
-- apply_due_pending_changes() cron job once due.

alter table pending_org_changes drop constraint pending_org_changes_change_type_check;
alter table pending_org_changes add constraint pending_org_changes_change_type_check check (change_type in (
  'transfer', 'promotion', 'karenz_start', 'karenz_return', 'contract_change', 'reorg', 'dependent_add', 'dependent_remove'
));

-- ── Angehörige:n hinzufügen: now effective-dated ─────────────────────
-- Return type changes uuid -> void (a deferred add has no row yet to
-- return an id for), which CREATE OR REPLACE can't do in place.
drop function if exists add_employee_dependent(jsonb);

create function add_employee_dependent(payload jsonb)
returns void language plpgsql as $$
declare
  v_employee_id uuid := (payload->>'employee_id')::uuid;
  v_employee_name text;
  v_effective_date date := coalesce(nullif(payload->>'effective_date', '')::date, current_date);
  v_dep_name text := (payload->>'first_name') || ' ' || (payload->>'last_name');
begin
  perform require_hr_admin();
  select first_name || ' ' || last_name into v_employee_name from employees where id = v_employee_id;
  if not found then
    raise exception 'Mitarbeiter:in nicht gefunden.';
  end if;

  if v_effective_date <= current_date then
    insert into employee_dependents (employee_id, first_name, last_name, relationship, sv_nummer, birth_date)
      values (
        v_employee_id, payload->>'first_name', payload->>'last_name', payload->>'relationship',
        nullif(payload->>'sv_nummer', ''), (payload->>'birth_date')::date
      );
  else
    insert into pending_org_changes (employee_id, change_type, effective_date, payload)
      values (v_employee_id, 'dependent_add', v_effective_date, payload);
  end if;

  insert into employee_history (employee_id, event_date, event_type, description)
    values (
      v_employee_id, v_effective_date, 'Stammdatenänderung',
      'Angehörige:r hinzugefügt: ' || v_dep_name || ' (' || (payload->>'relationship') || '), wirksam ab ' || v_effective_date
    );
  insert into audit_log (actor_user_id, actor_name, action, target_label, target_employee_id, details)
    values (
      auth.uid(), current_actor_name(), 'Angehörige:r hinzugefügt', v_employee_name, v_employee_id,
      v_dep_name || ' (' || (payload->>'relationship') || '), wirksam ab ' || v_effective_date
    );
end;
$$;

-- ── Angehörige:n entfernen: now effective-dated ──────────────────────
create or replace function delete_employee_dependent(payload jsonb)
returns void language plpgsql as $$
declare
  v_dep employee_dependents%rowtype;
  v_employee_name text;
  v_effective_date date := coalesce(nullif(payload->>'effective_date', '')::date, current_date);
begin
  perform require_hr_admin();
  select * into v_dep from employee_dependents where id = (payload->>'dependent_id')::uuid;
  if not found then
    raise exception 'Angehörige:r nicht gefunden.';
  end if;
  select first_name || ' ' || last_name into v_employee_name from employees where id = v_dep.employee_id;

  if v_effective_date <= current_date then
    delete from employee_dependents where id = v_dep.id;
  else
    insert into pending_org_changes (employee_id, change_type, effective_date, payload)
      values (v_dep.employee_id, 'dependent_remove', v_effective_date, jsonb_build_object('dependent_id', v_dep.id));
  end if;

  insert into employee_history (employee_id, event_date, event_type, description)
    values (
      v_dep.employee_id, v_effective_date, 'Stammdatenänderung',
      'Angehörige:r entfernt: ' || v_dep.first_name || ' ' || v_dep.last_name || ' (' || v_dep.relationship || '), wirksam ab ' || v_effective_date
    );
  insert into audit_log (actor_user_id, actor_name, action, target_label, target_employee_id, details)
    values (
      auth.uid(), current_actor_name(), 'Angehörige:r entfernt', v_employee_name, v_dep.employee_id,
      v_dep.first_name || ' ' || v_dep.last_name || ' (' || v_dep.relationship || '), wirksam ab ' || v_effective_date
    );
end;
$$;

-- ── apply_due_pending_changes: dependent_add/dependent_remove branches ──
create or replace function apply_due_pending_changes()
returns int
language plpgsql
security definer
set search_path = public
as $$
declare
  v_rec record;
  v_team_id uuid;
  v_division_id uuid;
  v_is_lead boolean;
  v_manager uuid;
  v_remaining int;
  v_applied_count int := 0;
begin
  for v_rec in
    select * from pending_org_changes
    where status = 'pending' and effective_date <= current_date
    order by created_at
  loop
    if v_rec.change_type = 'transfer' then
      select is_lead into v_is_lead from employees where id = v_rec.employee_id;
      select division_id into v_division_id from teams t join departments d on d.id = t.department_id
        where t.id = (v_rec.payload->>'new_team_id')::uuid;
      v_manager := resolve_manager_for((v_rec.payload->>'new_team_id')::uuid, v_is_lead, v_division_id);
      update employees set
        team_id = (v_rec.payload->>'new_team_id')::uuid,
        job_title = coalesce(nullif(v_rec.payload->>'new_title', ''), job_title),
        manager_id = v_manager
      where id = v_rec.employee_id;

    elsif v_rec.change_type = 'promotion' then
      update employees set
        job_title = coalesce(v_rec.payload->>'new_title', job_title),
        paygrade = coalesce((v_rec.payload->>'new_paygrade')::paygrade_type, paygrade)
      where id = v_rec.employee_id;

    elsif v_rec.change_type = 'karenz_start' then
      update employees set status = 'Karenz', karenz_return_date = (v_rec.payload->>'planned_return_date')::date
        where id = v_rec.employee_id;

    elsif v_rec.change_type = 'karenz_return' then
      select team_id, division_id, is_lead into v_team_id, v_division_id, v_is_lead
        from employees where id = v_rec.employee_id;
      v_manager := resolve_manager_for(v_team_id, v_is_lead, v_division_id);
      update employees set
        status = 'Aktiv',
        karenz_return_date = null,
        karenz_start_date = null,
        manager_id = v_manager,
        employment_type = coalesce((v_rec.payload->>'employment_type')::employment_type, employment_type),
        weekly_hours = coalesce((v_rec.payload->>'weekly_hours')::numeric, weekly_hours)
      where id = v_rec.employee_id;

    elsif v_rec.change_type = 'contract_change' then
      update employees set
        first_name = coalesce(v_rec.payload->'person'->>'first_name', first_name),
        last_name = coalesce(v_rec.payload->'person'->>'last_name', last_name),
        gender = coalesce((v_rec.payload->'person'->>'gender')::gender_type, gender),
        birth_date = coalesce((v_rec.payload->'person'->>'birth_date')::date, birth_date),
        sv_nummer = coalesce(v_rec.payload->'person'->>'sv_nummer', sv_nummer),
        nationality = coalesce(v_rec.payload->'person'->>'nationality', nationality),
        address = coalesce(v_rec.payload->'person'->>'address', address),
        postal_code = coalesce(v_rec.payload->'person'->>'postal_code', postal_code),
        city = coalesce(v_rec.payload->'person'->>'city', city),
        address_country = coalesce(v_rec.payload->'person'->>'address_country', address_country),
        email = coalesce(v_rec.payload->'person'->>'email', email),
        phone = coalesce(v_rec.payload->'person'->>'phone', phone),
        title_prefix = case when v_rec.payload->'person' ? 'title_prefix'
          then coalesce((select array_agg(elem) from jsonb_array_elements_text(v_rec.payload->'person'->'title_prefix') elem), '{}') else title_prefix end,
        title_suffix = case when v_rec.payload->'person' ? 'title_suffix'
          then coalesce((select array_agg(elem) from jsonb_array_elements_text(v_rec.payload->'person'->'title_suffix') elem), '{}') else title_suffix end,
        employment_type = coalesce((v_rec.payload->'contract'->>'employment_type')::employment_type, employment_type),
        weekly_hours = coalesce((v_rec.payload->'contract'->>'weekly_hours')::numeric, weekly_hours),
        contract_type = coalesce((v_rec.payload->'contract'->>'contract_type')::contract_type, contract_type),
        contract_end_date = case when v_rec.payload->'contract' ? 'contract_end_date'
          then nullif(v_rec.payload->'contract'->>'contract_end_date','')::date else contract_end_date end,
        worker_type = coalesce((v_rec.payload->'role'->>'worker_type')::worker_type, worker_type),
        collective_agreement = coalesce((v_rec.payload->'role'->>'collective_agreement')::collective_agreement, collective_agreement),
        work_days = case when v_rec.payload->'role' ? 'work_days'
          then coalesce((select array_agg(elem) from jsonb_array_elements_text(v_rec.payload->'role'->'work_days') elem), '{}') else work_days end,
        is_betriebsrat = coalesce((v_rec.payload->'role'->>'is_betriebsrat')::boolean, is_betriebsrat),
        has_dienstwagen = coalesce((v_rec.payload->'role'->>'has_dienstwagen')::boolean, has_dienstwagen),
        is_laterale_fuehrung = coalesce((v_rec.payload->'role'->>'is_laterale_fuehrung')::boolean, is_laterale_fuehrung),
        is_c_level = coalesce((v_rec.payload->'role'->>'is_c_level')::boolean, is_c_level)
      where id = v_rec.employee_id;

    elsif v_rec.change_type = 'dependent_add' then
      insert into employee_dependents (employee_id, first_name, last_name, relationship, sv_nummer, birth_date)
        values (
          v_rec.employee_id, v_rec.payload->>'first_name', v_rec.payload->>'last_name', v_rec.payload->>'relationship',
          nullif(v_rec.payload->>'sv_nummer', ''), (v_rec.payload->>'birth_date')::date
        );

    elsif v_rec.change_type = 'dependent_remove' then
      delete from employee_dependents where id = (v_rec.payload->>'dependent_id')::uuid;

    elsif v_rec.change_type = 'reorg' then
      select is_lead into v_is_lead from employees where id = v_rec.employee_id;
      select division_id into v_division_id from teams t join departments d on d.id = t.department_id
        where t.id = (v_rec.payload->>'target_team_id')::uuid;
      v_manager := resolve_manager_for((v_rec.payload->>'target_team_id')::uuid, v_is_lead, v_division_id);
      update employees set team_id = (v_rec.payload->>'target_team_id')::uuid, manager_id = v_manager
        where id = v_rec.employee_id;
    end if;

    update pending_org_changes set status = 'applied', applied_at = now() where id = v_rec.id;
    v_applied_count := v_applied_count + 1;

    if v_rec.reorg_scenario_id is not null then
      select count(*) into v_remaining from pending_org_changes
        where reorg_scenario_id = v_rec.reorg_scenario_id and status = 'pending';
      if v_remaining = 0 then
        update reorg_scenarios set applied = true, applied_at = now() where id = v_rec.reorg_scenario_id;
      end if;
    end if;
  end loop;

  return v_applied_count;
end;
$$;

revoke execute on function apply_due_pending_changes() from public, anon, authenticated;
grant execute on function apply_due_pending_changes() to service_role;
