insert into equipment_categories (name)
values
  ('Laptopy'),
  ('Tablety'),
  ('Akcesoria')
on conflict (name) do update
  set updated_at = now();

with categorized_items as (
  select
    i.id,
    case
      when c.name ilike '%laptop%'
        or c.name ilike '%macbook%'
        or lower(i.name) like '%macbook%'
      then 'Laptopy'
      when c.name ilike '%tablet%'
        or lower(i.name) like '%ipad%'
        or lower(i.name) like '%samsung%'
        or lower(i.name) like '%galaxy%'
      then 'Tablety'
      else 'Akcesoria'
    end as target_category_name
  from equipment_items i
  join equipment_categories c on c.id = i.category_id
)
update equipment_items i
set
  category_id = target_category.id,
  updated_at = now()
from categorized_items categorized
join equipment_categories target_category on target_category.name = categorized.target_category_name
where i.id = categorized.id
  and i.category_id <> target_category.id;

delete from equipment_categories c
where c.name not in ('Laptopy', 'Tablety', 'Akcesoria')
  and not exists (
    select 1
    from equipment_items i
    where i.category_id = c.id
  );
