-- Split the combined "Straße Nr, PLZ Ort" address string into three fields.
--
-- employees.address now holds only Straße + Hausnummer (still a single
-- free-text line); postal_code and city are their own columns so the UI
-- can offer them as separate inputs and reports/exports can filter or
-- group by them independently.
alter table employees add column if not exists postal_code text;
alter table employees add column if not exists city text;

-- Best-effort backfill for existing rows seeded in the old combined format
-- (supabase/seed.ts previously wrote "Straße Nr, PLZ Ort"). Only rewrites
-- rows that actually match that exact "<street>, <postal> <city>" shape;
-- anything else (already-split rows, hand-edited free text, no comma) is
-- left untouched for HR to fill in via "Daten ändern".
update employees
set
  postal_code = trim(split_part(split_part(address, ', ', 2), ' ', 1)),
  city = trim(substring(split_part(address, ', ', 2) from '\S+\s+(.*)$')),
  address = trim(split_part(address, ', ', 1))
where address ~ '^[^,]+,\s*\d{3,6}\s*[[:alpha:]].*$';

-- ── change_employee_data: recognize postal_code/city as person 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_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 ? '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_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
    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 postal_code/city 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
      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;
