begin;

set search_path to public;

create table if not exists speech_recognition_config (
  id bigint generated by default as identity primary key,
  tenant_id bigint not null,
  enabled boolean not null default true,
  base_url varchar(512),
  transcribe_path varchar(255) not null default '/v1/audio/transcriptions',
  task_status_path varchar(255) not null default '/v1/tasks/{task_id}',
  file_field_name varchar(64) not null default 'file',
  language varchar(32),
  response_format varchar(32) not null default 'json',
  model varchar(128),
  prompt text,
  hotwords text,
  timestamp_granularities varchar(128),
  enable_speaker_diarization boolean,
  enable_speaker_identification boolean,
  enable_text_cleanup boolean,
  temperature double precision,
  api_key varchar(512),
  api_key_header varchar(128) not null default 'X-API-Key',
  connect_timeout_seconds integer not null default 10,
  read_timeout_seconds integer not null default 300,
  task_timeout_seconds integer not null default 300,
  task_poll_interval_millis integer not null default 1500,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now(),
  constraint uk_speech_recognition_config_tenant unique (tenant_id)
);

alter table if exists speech_recognition_config add column if not exists response_format varchar(32) not null default 'json';
alter table if exists speech_recognition_config add column if not exists model varchar(128);
alter table if exists speech_recognition_config add column if not exists prompt text;
alter table if exists speech_recognition_config add column if not exists hotwords text;
alter table if exists speech_recognition_config add column if not exists timestamp_granularities varchar(128);
alter table if exists speech_recognition_config add column if not exists enable_speaker_diarization boolean;
alter table if exists speech_recognition_config add column if not exists enable_speaker_identification boolean;
alter table if exists speech_recognition_config add column if not exists enable_text_cleanup boolean;
alter table if exists speech_recognition_config add column if not exists temperature double precision;

do $$
declare
  v_system_parent_id bigint;
  v_menu_perm_id bigint;
  v_view_perm_id bigint;
  v_update_perm_id bigint;
begin
  perform setval('sys_permission_perm_id_seq', coalesce((select max(perm_id) from sys_permission), 0) + 1, false);
  perform setval('sys_role_permission_id_seq', coalesce((select max(id) from sys_role_permission), 0) + 1, false);

  select perm_id
    into v_system_parent_id
  from sys_permission
  where code = 'system'
    and coalesce(is_deleted, 0) = 0
  order by perm_id
  limit 1;

  if v_system_parent_id is null then
    insert into sys_permission (
      parent_id, name, code, perm_type, level, path, component, icon,
      sort_order, is_visible, status, description, meta, is_deleted, created_at, updated_at
    ) values (
      null, '系统管理', 'system', 'directory', 1, null, null, 'SettingOutlined',
      110, 1, 1, '系统管理目录', '{}'::jsonb, 0, now(), now()
    )
    returning perm_id into v_system_parent_id;
  end if;

  select perm_id
    into v_menu_perm_id
  from sys_permission
  where code = 'menu:speech-recognition-settings'
  order by perm_id
  limit 1;

  if v_menu_perm_id is null then
    insert into sys_permission (
      parent_id, name, code, perm_type, level, path, component, icon,
      sort_order, is_visible, status, description, meta, is_deleted, created_at, updated_at
    ) values (
      v_system_parent_id, '语音识别配置', 'menu:speech-recognition-settings', 'menu', 2,
      '/speech-recognition-settings', null, 'AudioOutlined', 8, 1, 1,
      '日报语音转文字服务配置页面', jsonb_build_object('tenantScoped', true), 0, now(), now()
    )
    returning perm_id into v_menu_perm_id;
  else
    update sys_permission
    set parent_id = v_system_parent_id,
        name = '语音识别配置',
        perm_type = 'menu',
        level = 2,
        path = '/speech-recognition-settings',
        component = null,
        icon = 'AudioOutlined',
        sort_order = 8,
        is_visible = 1,
        status = 1,
        description = '日报语音转文字服务配置页面',
        meta = jsonb_build_object('tenantScoped', true),
        is_deleted = 0,
        updated_at = now()
    where perm_id = v_menu_perm_id;
  end if;

  select perm_id
    into v_view_perm_id
  from sys_permission
  where code = 'speech_recognition_config:view'
  order by perm_id
  limit 1;

  if v_view_perm_id is null then
    insert into sys_permission (
      parent_id, name, code, perm_type, level, path, component, icon,
      sort_order, is_visible, status, description, meta, is_deleted, created_at, updated_at
    ) values (
      v_menu_perm_id, '查看语音识别配置', 'speech_recognition_config:view', 'button', 3,
      null, null, null, 1, 1, 1, '查看日报语音转文字服务配置', '{}'::jsonb, 0, now(), now()
    )
    returning perm_id into v_view_perm_id;
  else
    update sys_permission
    set parent_id = v_menu_perm_id,
        name = '查看语音识别配置',
        perm_type = 'button',
        level = 3,
        sort_order = 1,
        is_visible = 1,
        status = 1,
        description = '查看日报语音转文字服务配置',
        meta = '{}'::jsonb,
        is_deleted = 0,
        updated_at = now()
    where perm_id = v_view_perm_id;
  end if;

  select perm_id
    into v_update_perm_id
  from sys_permission
  where code = 'speech_recognition_config:update'
  order by perm_id
  limit 1;

  if v_update_perm_id is null then
    insert into sys_permission (
      parent_id, name, code, perm_type, level, path, component, icon,
      sort_order, is_visible, status, description, meta, is_deleted, created_at, updated_at
    ) values (
      v_menu_perm_id, '修改语音识别配置', 'speech_recognition_config:update', 'button', 3,
      null, null, null, 2, 1, 1, '保存日报语音转文字服务配置', '{}'::jsonb, 0, now(), now()
    )
    returning perm_id into v_update_perm_id;
  else
    update sys_permission
    set parent_id = v_menu_perm_id,
        name = '修改语音识别配置',
        perm_type = 'button',
        level = 3,
        sort_order = 2,
        is_visible = 1,
        status = 1,
        description = '保存日报语音转文字服务配置',
        meta = '{}'::jsonb,
        is_deleted = 0,
        updated_at = now()
    where perm_id = v_update_perm_id;
  end if;

  insert into sys_role_permission (role_id, perm_id, is_deleted, created_at, updated_at)
  select r.role_id, p.perm_id, 0, now(), now()
  from sys_role r
  cross join (
    select unnest(array[v_menu_perm_id, v_view_perm_id, v_update_perm_id]) as perm_id
  ) p
  where coalesce(r.is_deleted, 0) = 0
    and (
      r.role_code in ('TENANT_ADMIN', 'ADMIN', 'SYS_ADMIN', 'PLATFORM_ADMIN', 'SUPER_ADMIN')
      or r.role_name ilike '%管理员%'
      or r.role_name ilike '%admin%'
    )
    and p.perm_id is not null
    and not exists (
      select 1
      from sys_role_permission rp
      where rp.role_id = r.role_id
        and rp.perm_id = p.perm_id
    );

  update sys_role_permission
  set is_deleted = 0,
      updated_at = now()
  where perm_id in (v_menu_perm_id, v_view_perm_id, v_update_perm_id)
    and role_id in (
      select r.role_id
      from sys_role r
      where coalesce(r.is_deleted, 0) = 0
        and (
          r.role_code in ('TENANT_ADMIN', 'ADMIN', 'SYS_ADMIN', 'PLATFORM_ADMIN', 'SUPER_ADMIN')
          or r.role_name ilike '%管理员%'
          or r.role_name ilike '%admin%'
        )
    );
end $$;

commit;
