-- Enforce that team leaders and team members must be profiles with role = 'it_staff'

-- Function: validate_team_leader_is_it_staff
create or replace function public.validate_team_leader_is_it_staff()
returns trigger language plpgsql as $$
begin
  if new.leader_id is not null then
    perform 1 from public.profiles where id = new.leader_id and role = 'it_staff';
    if not found then
      raise exception 'team leader must have role "it_staff"';
    end if;
  end if;
  return new;
end;
$$;

-- Trigger on teams
drop trigger if exists trig_validate_team_leader on public.teams;
create trigger trig_validate_team_leader
before insert or update on public.teams
for each row execute function public.validate_team_leader_is_it_staff();


-- Function: validate_team_member_is_it_staff
create or replace function public.validate_team_member_is_it_staff()
returns trigger language plpgsql as $$
begin
  if new.user_id is not null then
    perform 1 from public.profiles where id = new.user_id and role = 'it_staff';
    if not found then
      raise exception 'team member must have role "it_staff"';
    end if;
  end if;
  return new;
end;
$$;

-- Trigger on team_members
drop trigger if exists trig_validate_team_member on public.team_members;
create trigger trig_validate_team_member
before insert or update on public.team_members
for each row execute function public.validate_team_member_is_it_staff();
