-- Smilegate PoC backoffice users. These are tool operators, not game players.

declare
  table_missing exception;
  pragma exception_init(table_missing, -955);
begin
  execute immediate q'[
    create table sg_tool_user (
      user_id       varchar2(100) not null,
      user_nm       varchar2(200) not null,
      role_code     varchar2(30) not null,
      password_hash varchar2(200) not null,
      enabled_yn    char(1) default 'Y' not null,
      created_at    timestamp default systimestamp not null,
      updated_at    timestamp default systimestamp not null,
      constraint sg_tool_user_pk primary key (user_id),
      constraint sg_tool_user_role_ck check (role_code in ('TEAM_LEAD', 'TEAM_MEMBER')),
      constraint sg_tool_user_enabled_ck check (enabled_yn in ('Y', 'N'))
    )
  ]';
exception
  when table_missing then null;
end;
/

merge into sg_tool_user target
using (
  select 'sg-teamlead' as user_id, 'SG Demo Team Lead' as user_nm,
         'TEAM_LEAD' as role_code,
         '{bcrypt}$2y$12$esdNRjiRo3ZxBnUGD1xrjuIFjCeCWcxlksDfdZpeImTsVtIdh/IJe' as password_hash
    from dual
  union all
  select 'sg-member', 'SG Demo Team Member', 'TEAM_MEMBER',
         '{bcrypt}$2y$12$esdNRjiRo3ZxBnUGD1xrjuIFjCeCWcxlksDfdZpeImTsVtIdh/IJe'
    from dual
) source
on (target.user_id = source.user_id)
when matched then update set
  target.user_nm = source.user_nm,
  target.role_code = source.role_code,
  target.password_hash = source.password_hash,
  target.enabled_yn = 'Y',
  target.updated_at = systimestamp
when not matched then insert (user_id, user_nm, role_code, password_hash, enabled_yn)
values (source.user_id, source.user_nm, source.role_code, source.password_hash, 'Y');

commit;
