alter table crm_sales_expansion
  add column if not exists employee_no varchar(50);

update crm_sales_expansion
set employee_no = concat('EMP', lpad(id::text, 6, '0'))
where employee_no is null or btrim(employee_no) = '';

with duplicated as (
  select
    id,
    row_number() over (partition by owner_user_id, employee_no order by id asc) as rn
  from crm_sales_expansion
)
update crm_sales_expansion s
set employee_no = concat(s.employee_no, '-', s.id)
from duplicated d
where s.id = d.id
  and d.rn > 1;

alter table crm_sales_expansion
  alter column employee_no set not null;

create unique index if not exists uk_crm_sales_expansion_owner_employee_no
  on crm_sales_expansion(owner_user_id, employee_no);

alter table crm_sales_expansion
  add column if not exists office_name varchar(100);

alter table crm_opportunity
  add column if not exists sales_expansion_id bigint;

create index if not exists idx_crm_opportunity_sales_expansion
  on crm_opportunity(sales_expansion_id);

do $$
begin
  if not exists (
    select 1
    from pg_constraint
    where conname = 'fk_crm_opportunity_sales_expansion'
  ) then
    alter table crm_opportunity
      add constraint fk_crm_opportunity_sales_expansion
      foreign key (sales_expansion_id) references crm_sales_expansion(id);
  end if;
end $$;
