-- Salary out of MVP scope (spec §4)
--
-- Decision: do NOT drop employees.monthly_salary_gross. This is a live
-- Supabase project that may already hold seeded/real rows with values in
-- this column; a destructive drop is unrecoverable and unnecessary to
-- achieve the actual goal (removing salary from the product surface).
-- Instead: relax the column so the app can stop supplying it, mark it
-- deprecated, and stop every RPC from reading/writing it. A future
-- migration MAY drop the column outright once it's confirmed nothing in
-- any environment still depends on it (tracked in docs/decisions).

alter table employees alter column monthly_salary_gross drop not null;
alter table employees drop constraint if exists employees_monthly_salary_gross_check;

comment on column employees.monthly_salary_gross is
  'DEPRECATED (2026 consolidation): salary is out of MVP scope. Column kept '
  'only because it may hold pre-existing data; the application no longer '
  'reads or writes it (see hire_employee/promote_employee). Candidate for '
  'a future DROP COLUMN once confirmed unused across all environments.';

-- hire_employee: stop requiring/writing salary.
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;
    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
  ) 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
  ) 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;
$$;

-- promote_employee: no longer accepts/writes new_salary; paygrade remains
-- (it's an organizational/functional classification, not a derived salary
-- figure — see §4 point 7).
create or replace function promote_employee(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_paygrade paygrade_type;
  v_name text;
  v_details text;
begin
  perform require_hr_admin();
  select paygrade, first_name || ' ' || last_name into v_old_paygrade, v_name from employees where id = v_employee_id;

  v_details := 'Neue Position: ' || (payload->>'new_title');
  if payload->>'new_paygrade' is not null and (payload->>'new_paygrade')::paygrade_type <> v_old_paygrade then
    v_details := v_details || ', neue Paygrade: ' || (payload->>'new_paygrade');
  end if;

  if v_effective_date <= current_date then
    update employees set
      job_title = payload->>'new_title',
      paygrade = coalesce((payload->>'new_paygrade')::paygrade_type, paygrade)
    where id = v_employee_id;
  else
    insert into pending_org_changes (employee_id, change_type, effective_date, payload)
      values (v_employee_id, 'promotion', v_effective_date,
        jsonb_build_object('new_title', payload->>'new_title', 'new_paygrade', payload->>'new_paygrade'));
  end if;

  insert into employee_history (employee_id, event_date, event_type, description)
    values (v_employee_id, v_effective_date, 'Beförderung', v_details);

  insert into audit_log (actor_user_id, actor_name, action, target_label, target_employee_id, details)
    values (auth.uid(), current_actor_name(), 'Beförderung', v_name, v_employee_id, v_details);
end;
$$;
