-- Two data-integrity rules named explicitly in the spec (§3.7, §11 test scenarios #14 and #17) that had no enforcement
-- anywhere — not in the UI, not in a Server Action, not as a DB constraint:
--
--   1. "Rückkehr darf nicht vor Beginn der Karenz liegen" — there was no
--      column tracking when a Karenz period actually started (only a
--      free-text history row), so this could not be validated at all.
--   2. "Historieneinträge dürfen nicht vor dem Eintritt liegen" — nothing
--      stopped an employee_history row from being inserted with an
--      event_date earlier than that employee's entry_date.

-- ── 1. Track karenz_start_date; validate return against it ──────────
alter table employees add column if not exists karenz_start_date date;

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_start_date = v_start_date,
      karenz_return_date = (payload->>'planned_return_date')::date
      where id = v_employee_id;
  else
    update employees set karenz_start_date = v_start_date where id = v_employee_id;
    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;
$$;

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

  if v_karenz_start is not null and v_new_return_date <= v_karenz_start then
    raise exception 'Das Rückkehrdatum muss nach dem Karenzbeginn (%) liegen.', v_karenz_start;
  end if;

  update employees set karenz_return_date = v_new_return_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;
  v_karenz_start date;
begin
  perform require_hr_admin();
  select first_name || ' ' || last_name, team_id, division_id, is_lead, karenz_start_date
    into v_name, v_team_id, v_division_id, v_is_lead, v_karenz_start
    from employees where id = v_employee_id;

  if v_karenz_start is not null and v_return_date <= v_karenz_start then
    raise exception 'Das Rückkehrdatum muss nach dem Karenzbeginn (%) liegen.', v_karenz_start;
  end if;

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

-- apply_due_pending_changes: clear karenz_start_date once the deferred
-- return actually applies (mirrors the immediate branch above).
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),
        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;
$$;

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

-- ── 2. History entries may never predate the employee's entry date ───
create or replace function fn_check_history_not_before_entry()
returns trigger
language plpgsql
as $$
declare
  v_entry_date date;
begin
  select entry_date into v_entry_date from employees where id = new.employee_id;
  if v_entry_date is not null and new.event_date < v_entry_date then
    raise exception 'Historieneintrag (%) darf nicht vor dem Eintrittsdatum (%) liegen.', new.event_date, v_entry_date;
  end if;
  return new;
end;
$$;

drop trigger if exists trg_history_not_before_entry on employee_history;
create trigger trg_history_not_before_entry
before insert on employee_history
for each row execute function fn_check_history_not_before_entry();
