-- ==========================================================================
-- Agencia PSI — Migracao: campo "Observacao" nativo no commitment Sessao
-- ==========================================================================
-- Antes: o commitment determinado 'Sessao' (is_native=true, native_key='session')
-- nao tinha campos extras default. Os outros nativos (Leitura, Supervisao, Aula,
-- Analise Pessoal) ja vinham com 'notes' (Observacao, textarea) — Sessao era
-- a unica excecao.
--
-- O AgendaEventDialog tinha uma textarea hard-coded "Observacao" no form, fora
-- do mecanismo de extra_fields. Pra padronizar (e pra que a Observacao da
-- sessao siga o mesmo storage que os outros commitments: agenda_eventos.extra_fields),
-- a textarea hardcoded foi removida do .vue e Sessao agora ganha 'notes' como
-- campo extra default.
--
-- Esta migracao:
-- 1. Adiciona 'notes' (Observacao, textarea) em TODOS os commitments Sessao
--    existentes (idempotente — so insere se ainda nao houver).
-- 2. Atualiza a funcao seed_determined_commitments pra que novos tenants criados
--    daqui pra frente ja venham com 'notes' no Sessao por padrao.
-- ==========================================================================

-- ──────────────────────────────────────────────────────────────────────────
-- 1. Backfill — adiciona 'notes' nos commitments Sessao ja existentes
-- ──────────────────────────────────────────────────────────────────────────
INSERT INTO public.determined_commitment_fields (tenant_id, commitment_id, key, label, field_type, required, sort_order)
SELECT dc.tenant_id, dc.id, 'notes', 'Observação', 'textarea', false, 30
FROM public.determined_commitments dc
WHERE dc.is_native = true
  AND dc.native_key = 'session'
  AND NOT EXISTS (
      SELECT 1 FROM public.determined_commitment_fields f
      WHERE f.commitment_id = dc.id AND f.key = 'notes'
  );


-- ──────────────────────────────────────────────────────────────────────────
-- 2. Forward-fix — funcao seed_determined_commitments inclui 'notes' em Sessao
-- ──────────────────────────────────────────────────────────────────────────
CREATE OR REPLACE FUNCTION public.seed_determined_commitments(p_tenant_id uuid) RETURNS void
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
declare
  v_id uuid;
begin
  -- Sessão (locked + sempre ativa)
  if not exists (
    select 1 from public.determined_commitments
    where tenant_id = p_tenant_id and is_native = true and native_key = 'session'
  ) then
    insert into public.determined_commitments
      (tenant_id, is_native, native_key, is_locked, active, name, description)
    values
      (p_tenant_id, true, 'session', true, true, 'Sessão', 'Sessão com paciente');
  end if;

  -- Leitura
  if not exists (
    select 1 from public.determined_commitments
    where tenant_id = p_tenant_id and is_native = true and native_key = 'reading'
  ) then
    insert into public.determined_commitments
      (tenant_id, is_native, native_key, is_locked, active, name, description)
    values
      (p_tenant_id, true, 'reading', false, true, 'Leitura', 'Praticar leitura');
  end if;

  -- Supervisão
  if not exists (
    select 1 from public.determined_commitments
    where tenant_id = p_tenant_id and is_native = true and native_key = 'supervision'
  ) then
    insert into public.determined_commitments
      (tenant_id, is_native, native_key, is_locked, active, name, description)
    values
      (p_tenant_id, true, 'supervision', false, true, 'Supervisão', 'Supervisão');
  end if;

  -- Aula
  if not exists (
    select 1 from public.determined_commitments
    where tenant_id = p_tenant_id and is_native = true and native_key = 'class'
  ) then
    insert into public.determined_commitments
      (tenant_id, is_native, native_key, is_locked, active, name, description)
    values
      (p_tenant_id, true, 'class', false, false, 'Aula', 'Dar aula');
  end if;

  -- Análise pessoal
  if not exists (
    select 1 from public.determined_commitments
    where tenant_id = p_tenant_id and is_native = true and native_key = 'analysis'
  ) then
    insert into public.determined_commitments
      (tenant_id, is_native, native_key, is_locked, active, name, description)
    values
      (p_tenant_id, true, 'analysis', false, true, 'Análise Pessoal', 'Minha análise pessoal');
  end if;

  -- -------------------------------------------------------
  -- Campos padrão (idempotentes por (commitment_id, key))
  -- -------------------------------------------------------

  -- Sessão (NOVO em 2026-05-11: 'notes' como Observação default)
  select id into v_id
  from public.determined_commitments
  where tenant_id = p_tenant_id and is_native = true and native_key = 'session'
  limit 1;

  if v_id is not null then
    if not exists (select 1 from public.determined_commitment_fields where commitment_id = v_id and key = 'notes') then
      insert into public.determined_commitment_fields (tenant_id, commitment_id, key, label, field_type, required, sort_order)
      values (p_tenant_id, v_id, 'notes', 'Observação', 'textarea', false, 30);
    end if;
  end if;

  -- Leitura
  select id into v_id
  from public.determined_commitments
  where tenant_id = p_tenant_id and is_native = true and native_key = 'reading'
  limit 1;

  if v_id is not null then
    if not exists (select 1 from public.determined_commitment_fields where commitment_id = v_id and key = 'book') then
      insert into public.determined_commitment_fields (tenant_id, commitment_id, key, label, field_type, required, sort_order)
      values (p_tenant_id, v_id, 'book', 'Livro', 'text', false, 10);
    end if;

    if not exists (select 1 from public.determined_commitment_fields where commitment_id = v_id and key = 'author') then
      insert into public.determined_commitment_fields (tenant_id, commitment_id, key, label, field_type, required, sort_order)
      values (p_tenant_id, v_id, 'author', 'Autor', 'text', false, 20);
    end if;

    if not exists (select 1 from public.determined_commitment_fields where commitment_id = v_id and key = 'notes') then
      insert into public.determined_commitment_fields (tenant_id, commitment_id, key, label, field_type, required, sort_order)
      values (p_tenant_id, v_id, 'notes', 'Observação', 'textarea', false, 30);
    end if;
  end if;

  -- Supervisão
  select id into v_id
  from public.determined_commitments
  where tenant_id = p_tenant_id and is_native = true and native_key = 'supervision'
  limit 1;

  if v_id is not null then
    if not exists (select 1 from public.determined_commitment_fields where commitment_id = v_id and key = 'supervisor') then
      insert into public.determined_commitment_fields (tenant_id, commitment_id, key, label, field_type, required, sort_order)
      values (p_tenant_id, v_id, 'supervisor', 'Supervisor', 'text', false, 10);
    end if;

    if not exists (select 1 from public.determined_commitment_fields where commitment_id = v_id and key = 'topic') then
      insert into public.determined_commitment_fields (tenant_id, commitment_id, key, label, field_type, required, sort_order)
      values (p_tenant_id, v_id, 'topic', 'Assunto', 'text', false, 20);
    end if;

    if not exists (select 1 from public.determined_commitment_fields where commitment_id = v_id and key = 'notes') then
      insert into public.determined_commitment_fields (tenant_id, commitment_id, key, label, field_type, required, sort_order)
      values (p_tenant_id, v_id, 'notes', 'Observação', 'textarea', false, 30);
    end if;
  end if;

  -- Aula
  select id into v_id
  from public.determined_commitments
  where tenant_id = p_tenant_id and is_native = true and native_key = 'class'
  limit 1;

  if v_id is not null then
    if not exists (select 1 from public.determined_commitment_fields where commitment_id = v_id and key = 'theme') then
      insert into public.determined_commitment_fields (tenant_id, commitment_id, key, label, field_type, required, sort_order)
      values (p_tenant_id, v_id, 'theme', 'Tema', 'text', false, 10);
    end if;

    if not exists (select 1 from public.determined_commitment_fields where commitment_id = v_id and key = 'group') then
      insert into public.determined_commitment_fields (tenant_id, commitment_id, key, label, field_type, required, sort_order)
      values (p_tenant_id, v_id, 'group', 'Turma', 'text', false, 20);
    end if;

    if not exists (select 1 from public.determined_commitment_fields where commitment_id = v_id and key = 'notes') then
      insert into public.determined_commitment_fields (tenant_id, commitment_id, key, label, field_type, required, sort_order)
      values (p_tenant_id, v_id, 'notes', 'Observação', 'textarea', false, 30);
    end if;
  end if;

  -- Análise
  select id into v_id
  from public.determined_commitments
  where tenant_id = p_tenant_id and is_native = true and native_key = 'analysis'
  limit 1;

  if v_id is not null then
    if not exists (select 1 from public.determined_commitment_fields where commitment_id = v_id and key = 'analyst') then
      insert into public.determined_commitment_fields (tenant_id, commitment_id, key, label, field_type, required, sort_order)
      values (p_tenant_id, v_id, 'analyst', 'Analista', 'text', false, 10);
    end if;

    if not exists (select 1 from public.determined_commitment_fields where commitment_id = v_id and key = 'focus') then
      insert into public.determined_commitment_fields (tenant_id, commitment_id, key, label, field_type, required, sort_order)
      values (p_tenant_id, v_id, 'focus', 'Foco', 'text', false, 20);
    end if;

    if not exists (select 1 from public.determined_commitment_fields where commitment_id = v_id and key = 'notes') then
      insert into public.determined_commitment_fields (tenant_id, commitment_id, key, label, field_type, required, sort_order)
      values (p_tenant_id, v_id, 'notes', 'Observação', 'textarea', false, 30);
    end if;
  end if;
end;
$$;
