-- Fix effective-dating for Versetzung, Karenz (start + return), Daten
-- ändern, and Reorganisation (spec §3.3, §7.14).
--
-- Pattern used throughout: if the effective/return date is today or in the
-- past, behave exactly as before (immediate write). If it's in the future,
-- skip the `update employees` and instead record the intended change in
-- pending_org_changes; employee_history/audit_log are written immediately
-- either way, dated with the effective date (this is what already drives
-- the "zukünftig" badge in the Historie tab — unchanged). A separate
-- apply_due_pending_changes() function (called by a scheduled job) applies
-- due rows once their date arrives, re-resolving manager_id fresh at apply
-- time rather than trusting a value computed when the change was requested.

-- ── Versetzung ───────────────────────────────────────────────────
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_effective_date date := (payload->>'effective_date')::date;
  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;

  if v_effective_date <= current_date then
    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;
  else
    insert into pending_org_changes (employee_id, change_type, effective_date, payload)
      values (v_employee_id, 'transfer', v_effective_date,
        jsonb_build_object('new_team_id', v_new_team_id, 'new_title', payload->>'new_title'));
  end if;

  insert into employee_history (employee_id, event_date, event_type, description)
    values (v_employee_id, v_effective_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;
$$;

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

  if v_start_date <= current_date then
    update employees set status = 'Karenz', karenz_return_date = (payload->>'planned_return_date')::date
      where id = v_employee_id;
  else
    insert into pending_org_changes (employee_id, change_type, effective_date, payload)
      values (v_employee_id, 'karenz_start', v_start_date,
        jsonb_build_object('planned_return_date', payload->>'planned_return_date'));
  end if;

  insert into employee_history (employee_id, event_date, event_type, description)
    values (v_employee_id, v_start_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;
$$;

-- ── Rückkehr aus Karenz ──────────────────────────────────────────
-- status/manager_id/karenz_return_date already correctly waited for the
-- return date; employment_type/weekly_hours did not (fixed here).
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
    -- Only record the planned date now; the employment-mode change itself
    -- (and the status/manager flip) waits for record_karenz_return's
    -- effective date, applied later by apply_due_pending_changes().
    update employees set karenz_return_date = v_return_date where id = v_employee_id;
    insert into pending_org_changes (employee_id, change_type, effective_date, payload)
      values (v_employee_id, 'karenz_return', v_return_date,
        jsonb_build_object('employment_type', v_employment_type, 'weekly_hours', v_weekly_hours));
  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 ─────────────────────────────────────────────────
create or replace function change_employee_data(payload jsonb)
returns void language plpgsql as $$
declare
  v_employee_id uuid := (payload->>'employee_id')::uuid;
  v_effective_date date := coalesce(nullif(payload->>'effective_date', '')::date, current_date);
  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';
  v_immediate boolean;
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;
  v_immediate := v_effective_date <= current_date;

  if v_person ? 'first_name' and (v_person->>'first_name') <> v_old.first_name then v_person_changes := array_append(v_person_changes, 'Vorname'); end if;
  if v_person ? 'last_name' and (v_person->>'last_name') <> v_old.last_name then v_person_changes := array_append(v_person_changes, 'Nachname'); end if;
  if v_person ? 'gender' and (v_person->>'gender') <> v_old.gender::text then v_person_changes := array_append(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 := array_append(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 := array_append(v_person_changes, 'SV-Nummer'); end if;
  if v_person ? 'nationality' and (v_person->>'nationality') <> v_old.nationality then v_person_changes := array_append(v_person_changes, 'Staatsbürgerschaft'); end if;
  if v_person ? 'address' and coalesce(v_person->>'address','') <> coalesce(v_old.address,'') then v_person_changes := array_append(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 := array_append(v_person_changes, 'Land'); end if;
  if v_person ? 'email' and (v_person->>'email') <> v_old.email then v_person_changes := array_append(v_person_changes, 'E-Mail'); end if;
  if v_person ? 'phone' and coalesce(v_person->>'phone','') <> coalesce(v_old.phone,'') then v_person_changes := array_append(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 := array_append(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 := array_append(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 := array_append(v_contract_changes, 'Vertragsart'); end if;
  if v_contract ? 'contract_end_date' and coalesce(nullif(v_contract->>'contract_end_date','')::date::text,'') <> coalesce(v_old.contract_end_date::text,'') then v_contract_changes := array_append(v_contract_changes, 'Befristet bis'); end if;

  if v_immediate then
    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;
  elsif array_length(v_person_changes, 1) > 0 or array_length(v_contract_changes, 1) > 0 then
    insert into pending_org_changes (employee_id, change_type, effective_date, payload)
      values (v_employee_id, 'contract_change', v_effective_date, payload);
  end if;

  if array_length(v_person_changes, 1) > 0 then
    insert into employee_history (employee_id, event_date, event_type, description)
      values (v_employee_id, v_effective_date, 'Stammdatenänderung', 'Geänderte Felder: ' || array_to_string(v_person_changes, ', ') || ', 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(), 'Stammdatenänderung', v_name, v_employee_id, array_to_string(v_person_changes, ', ') || ', wirksam ab ' || v_effective_date);
  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, v_effective_date, 'Vertragsänderung', 'Geänderte Felder: ' || array_to_string(v_contract_changes, ', ') || ', 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(), 'Vertragsänderung', v_name, v_employee_id, array_to_string(v_contract_changes, ', ') || ', wirksam ab ' || v_effective_date);
  end if;
end;
$$;

-- ── Reorganisation ───────────────────────────────────────────────
-- Immediate moves (effective_date <= today) behave exactly as before.
-- Future-dated scenarios write no employee mutations at all yet; one
-- pending_org_changes row per affected employee is queued instead, and
-- reorg_scenarios.applied stays false until every one of them is applied.
create or replace function apply_reorg(payload jsonb)
returns uuid language plpgsql as $$
declare
  v_scenario_id uuid;
  v_effective_date date := (payload->>'effective_date')::date;
  v_immediate boolean := (payload->>'effective_date')::date <= current_date;
  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', v_effective_date, auth.uid(), v_immediate, case when v_immediate then now() else null end)
    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
      ));

      if v_immediate then
        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;
      else
        insert into pending_org_changes (employee_id, change_type, effective_date, payload, reorg_scenario_id)
          values (v_employee_id::uuid, 'reorg', v_effective_date,
            jsonb_build_object('target_team_id', v_target_team_id), v_scenario_id);
      end if;

      insert into employee_history (employee_id, event_date, event_type, description, reorg_scenario_id)
        values (v_employee_id::uuid, v_effective_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;
$$;

-- ── Applies every due pending change ─────────────────────────────
-- Invoked by the /api/cron/apply-pending-changes route handler (Vercel
-- Cron, daily) using the service-role client — this is a system process,
-- not a user action, so it does not go through require_hr_admin(); it is
-- SECURITY DEFINER precisely so it can run outside any HR user's session.
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,
        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),
        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),
        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
      where id = v_rec.employee_id;

    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;
$$;

-- This bypasses RLS (SECURITY DEFINER) by design so the daily cron job can
-- run it without any HR user session — which means it must NOT be callable
-- by ordinary app roles (an authenticated HR user calling it early would
-- force-apply not-yet-due changes ahead of their effective date).
revoke execute on function apply_due_pending_changes() from public;
revoke execute on function apply_due_pending_changes() from anon;
revoke execute on function apply_due_pending_changes() from authenticated;
grant execute on function apply_due_pending_changes() to service_role;
