-- Position validity window + delete capability.
--
--   1. Positions had no "gültig ab" (valid_from) date — nothing recorded
--      since when a position is actually meant to be active, so a position
--      created today for a future need could immediately be staffed/hired
--      into.
--   2. There was no way to remove a position again once created (no UI, no
--      Server Action, no RPC) — a mis-created or no-longer-needed open
--      requisition was stuck forever.
--   3. Neither staff_position_internally nor hire_employee checked the
--      position's validity window before assigning an employee to it.

alter table positions add column if not exists valid_from date not null default current_date;

-- ── Position ausschreiben: now records valid_from ────────────────
create or replace function create_position(payload jsonb)
returns uuid language plpgsql as $$
declare
  v_id uuid;
  v_superior_id uuid := (payload->>'superior_employee_id')::uuid;
  v_is_lead boolean := coalesce((payload->>'is_lead')::boolean, false);
  v_team_id uuid;
  v_valid_from date := coalesce(nullif(payload->>'valid_from', '')::date, current_date);
begin
  perform require_hr_admin();

  if v_is_lead then
    v_team_id := (payload->>'team_id')::uuid;
  else
    select team_id into v_team_id from employees where id = v_superior_id;
  end if;

  insert into positions (title, team_id, is_lead, reports_to_employee_id, valid_from)
    values (payload->>'title', v_team_id, v_is_lead, v_superior_id, v_valid_from)
    returning id into v_id;

  insert into audit_log (actor_user_id, actor_name, action, target_label, details)
    values (auth.uid(), current_actor_name(), 'Ausschreibung', payload->>'title', 'Position ausgeschrieben, gültig ab ' || v_valid_from);

  return v_id;
end;
$$;

-- ── Position löschen ───────────────────────────────────────────────
-- Only open (unfilled) positions can be deleted — a filled position is
-- already tied to an employee's history/audit trail and to whoever holds it.
create or replace function delete_position(payload jsonb)
returns void language plpgsql as $$
declare
  v_position record;
begin
  perform require_hr_admin();

  select * into v_position from positions where id = (payload->>'position_id')::uuid;
  if not found then
    raise exception 'Position nicht gefunden.';
  end if;
  if v_position.status <> 'open' then
    raise exception 'Nur offene Positionen können gelöscht werden.';
  end if;

  delete from positions where id = v_position.id;

  insert into audit_log (actor_user_id, actor_name, action, target_label, details)
    values (auth.uid(), current_actor_name(), 'Position gelöscht', v_position.title, 'Position ' || v_position.position_number || ' gelöscht');
end;
$$;

-- ── Intern besetzen: reject if the position isn't valid yet ─────────
create or replace function staff_position_internally(payload jsonb)
returns void language plpgsql as $$
declare
  v_position record;
  v_employee_id uuid := (payload->>'employee_id')::uuid;
  v_manager uuid;
  v_name text;
begin
  perform require_hr_admin();
  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 v_position.valid_from > current_date then
    raise exception 'Die Position ist erst ab % gültig.', to_char(v_position.valid_from, 'DD.MM.YYYY');
  end if;
  select first_name || ' ' || last_name into v_name from employees where id = v_employee_id;

  v_manager := resolve_manager_for(v_position.team_id, v_position.is_lead, v_position.division_id);

  update employees set
    team_id = v_position.team_id,
    job_title = v_position.title,
    source = 'Intern',
    is_lead = case when v_position.is_lead then true else is_lead end,
    org_level = case when v_position.is_lead then 2 else org_level end,
    manager_id = v_manager
  where id = v_employee_id;

  if v_position.is_lead then
    update employees set manager_id = v_employee_id
      where team_id = v_position.team_id and id <> v_employee_id and is_lead = false and status <> 'Ausgetreten';
  end if;

  update positions set status = 'filled', filled_at = now(), filled_by_employee_id = v_employee_id
    where id = v_position.id;

  insert into employee_history (employee_id, event_date, event_type, description)
    values (v_employee_id, current_date, 'Versetzung', 'Interne Besetzung: ' || v_position.title);

  insert into audit_log (actor_user_id, actor_name, action, target_label, target_employee_id, details)
    values (auth.uid(), current_actor_name(), 'Interne Besetzung', v_name, v_employee_id, v_position.title);
end;
$$;

-- ── Neueinstellung: reject if entry_date precedes the position's validity ──
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
  ) 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;
$$;
