-- "Rolle & Anstellung" — role/employment classification that HR tracked
-- outside the system until now: worker category (Angestellte:r vs.
-- Arbeiter:in), collective agreement, contracted work days, and a handful
-- of eligibility/reporting flags (Betriebsrat, Dienstwagen, laterale
-- Führung, C-Level).

create type worker_type as enum ('Angestellte:r', 'Arbeiter:in');
create type collective_agreement as enum ('Handel', 'Süßwaren');

alter table employees add column if not exists worker_type worker_type not null default 'Angestellte:r';
alter table employees add column if not exists collective_agreement collective_agreement not null default 'Handel';
alter table employees add column if not exists work_days text[] not null default '{Mo,Di,Mi,Do,Fr}';
alter table employees add column if not exists is_betriebsrat boolean not null default false;
alter table employees add column if not exists has_dienstwagen boolean not null default false;
alter table employees add column if not exists is_laterale_fuehrung boolean not null default false;
alter table employees add column if not exists is_c_level boolean not null default false;

alter table employees add constraint chk_work_days_valid check (
  work_days <@ array['Mo','Di','Mi','Do','Fr','Sa','So']::text[] and cardinality(work_days) > 0
);

-- ── Neueinstellung: accepts the new role/employment fields ─────────────
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_job_title text;
  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;
    if (payload->>'entry_date')::date < v_position.valid_from then
      raise exception 'Das Eintrittsdatum darf nicht vor dem Gültigkeitsbeginn der Position (%) liegen.', to_char(v_position.valid_from, 'DD.MM.YYYY');
    end if;
    v_team_id := v_position.team_id;
    v_division_id := v_position.division_id;
    v_job_title := coalesce(payload->>'job_title', v_position.title);
  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;
    v_job_title := payload->>'job_title';
  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, contract_type, contract_end_date,
    paygrade, source, status, entry_date,
    worker_type, collective_agreement, work_days,
    is_betriebsrat, has_dienstwagen, is_laterale_fuehrung, is_c_level
  ) 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, v_job_title, (payload->>'location_id')::uuid,
    v_manager, 3, false,
    coalesce((payload->>'employment_type')::employment_type, 'Vollzeit'),
    coalesce((payload->>'weekly_hours')::numeric, 38.5),
    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)::employment_status,
    (payload->>'entry_date')::date,
    coalesce((payload->>'worker_type')::worker_type, 'Angestellte:r'),
    coalesce((payload->>'collective_agreement')::collective_agreement, 'Handel'),
    case when payload ? 'work_days' then coalesce((select array_agg(elem) from jsonb_array_elements_text(payload->'work_days') elem), '{}') else '{Mo,Di,Mi,Do,Fr}' end,
    coalesce((payload->>'is_betriebsrat')::boolean, false),
    coalesce((payload->>'has_dienstwagen')::boolean, false),
    coalesce((payload->>'is_laterale_fuehrung')::boolean, false),
    coalesce((payload->>'is_c_level')::boolean, false)
  ) 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 ' || v_job_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;
$$;

-- ── Daten ändern: recognize a "role" section alongside person/contract ──
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_role jsonb := payload->'role';
  v_immediate boolean;
  v_new_work_days text[];
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 ? 'postal_code' and coalesce(v_person->>'postal_code','') <> coalesce(v_old.postal_code,'') then v_person_changes := array_append(v_person_changes, 'Postleitzahl'); end if;
  if v_person ? 'city' and coalesce(v_person->>'city','') <> coalesce(v_old.city,'') then v_person_changes := array_append(v_person_changes, 'Ort'); 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_role ? 'worker_type' and (v_role->>'worker_type') <> v_old.worker_type::text then v_contract_changes := array_append(v_contract_changes, 'Angestellte:r/Arbeiter:in'); end if;
  if v_role ? 'collective_agreement' and (v_role->>'collective_agreement') <> v_old.collective_agreement::text then v_contract_changes := array_append(v_contract_changes, 'Kollektivvertrag'); end if;
  if v_role ? 'work_days' then
    v_new_work_days := coalesce((select array_agg(elem) from jsonb_array_elements_text(v_role->'work_days') elem), '{}');
    if v_new_work_days is distinct from v_old.work_days then v_contract_changes := array_append(v_contract_changes, 'Arbeitstage'); end if;
  end if;
  if v_role ? 'is_betriebsrat' and (v_role->>'is_betriebsrat')::boolean <> v_old.is_betriebsrat then v_contract_changes := array_append(v_contract_changes, 'Betriebsrat'); end if;
  if v_role ? 'has_dienstwagen' and (v_role->>'has_dienstwagen')::boolean <> v_old.has_dienstwagen then v_contract_changes := array_append(v_contract_changes, 'Dienstwagen'); end if;
  if v_role ? 'is_laterale_fuehrung' and (v_role->>'is_laterale_fuehrung')::boolean <> v_old.is_laterale_fuehrung then v_contract_changes := array_append(v_contract_changes, 'Laterale Führung'); end if;
  if v_role ? 'is_c_level' and (v_role->>'is_c_level')::boolean <> v_old.is_c_level then v_contract_changes := array_append(v_contract_changes, 'C-Level'); 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),
      postal_code = coalesce(v_person->>'postal_code', postal_code),
      city = coalesce(v_person->>'city', city),
      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,
      worker_type = coalesce((v_role->>'worker_type')::worker_type, worker_type),
      collective_agreement = coalesce((v_role->>'collective_agreement')::collective_agreement, collective_agreement),
      work_days = case when v_role ? 'work_days' then v_new_work_days else work_days end,
      is_betriebsrat = coalesce((v_role->>'is_betriebsrat')::boolean, is_betriebsrat),
      has_dienstwagen = coalesce((v_role->>'has_dienstwagen')::boolean, has_dienstwagen),
      is_laterale_fuehrung = coalesce((v_role->>'is_laterale_fuehrung')::boolean, is_laterale_fuehrung),
      is_c_level = coalesce((v_role->>'is_c_level')::boolean, is_c_level)
    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;
$$;

-- ── apply_due_pending_changes: mirror the same role-field handling in the
-- deferred contract_change branch ──
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),
        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 = '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;
