-- Seguimiento de Impuestos GLM
-- Actualización incremental: retirar WhatsApp y habilitar Google Chat.
-- Ejecutar después de actualizacion_bamboohr_google_calendar.sql.

begin;

alter table public.tax_contacts
  add column if not exists google_chat_enabled boolean not null default true;

alter table public.tax_contacts
  alter column whatsapp_enabled set default false;

-- La nueva operación deja de usar WhatsApp. Se conserva la información histórica
-- para no destruir datos ni bitácoras anteriores.
update public.tax_contacts
set
  whatsapp_enabled = false,
  google_chat_enabled = case
    when email_enabled = true and email is not null and length(trim(email)) > 3 then true
    else false
  end;

alter table public.tax_contacts
  drop constraint if exists tax_contacts_google_chat_email_when_enabled;

alter table public.tax_contacts
  add constraint tax_contacts_google_chat_email_when_enabled
  check (not google_chat_enabled or length(trim(coalesce(email, ''))) > 3);

alter table public.tax_notification_log
  drop constraint if exists tax_notification_log_channel_check;

alter table public.tax_notification_log
  add constraint tax_notification_log_channel_check
  check (channel in ('email', 'google_chat', 'whatsapp'));

-- CREATE OR REPLACE no permite cambiar las columnas retornadas, por eso se elimina
-- y se recrea la RPC usada por n8n.
drop function if exists public.tax_due_reminders(date);

create function public.tax_due_reminders(p_run_date date default current_date)
returns table (
  obligation_id uuid,
  contact_id uuid,
  alert_date date,
  alert_type text,
  due_date date,
  description text,
  category text,
  country_name text,
  country_code text,
  contact_name text,
  contact_email text,
  email_enabled boolean,
  google_chat_enabled boolean
)
language sql
stable
security definer
set search_path = ''
as $$
  with due as (
    select
      obligation.id,
      obligation.due_date,
      obligation.description,
      obligation.category,
      obligation.country_id,
      country.name as country_name,
      country.code as country_code,
      case
        when p_run_date = obligation.due_date then 'same_day'
        else 'previous_wednesday'
      end as alert_type
    from public.tax_obligations obligation
    join public.tax_countries country on country.id = obligation.country_id
    where obligation.active = true
      and (
        p_run_date = obligation.due_date
        or p_run_date = public.tax_previous_wednesday(obligation.due_date)
      )
  )
  select
    due.id as obligation_id,
    contact.id as contact_id,
    p_run_date as alert_date,
    due.alert_type,
    due.due_date,
    due.description,
    due.category,
    due.country_name,
    due.country_code,
    contact.full_name as contact_name,
    contact.email as contact_email,
    (
      contact.email_enabled
      and contact.email is not null
      and not exists (
        select 1
        from public.tax_notification_log log
        where log.obligation_id = due.id
          and log.contact_id = contact.id
          and log.alert_date = p_run_date
          and log.channel = 'email'
          and log.status = 'sent'
      )
    ) as email_enabled,
    (
      contact.google_chat_enabled
      and contact.email is not null
      and not exists (
        select 1
        from public.tax_notification_log log
        where log.obligation_id = due.id
          and log.contact_id = contact.id
          and log.alert_date = p_run_date
          and log.channel = 'google_chat'
          and log.status = 'sent'
      )
    ) as google_chat_enabled
  from due
  join public.tax_contacts contact on contact.active = true
  join public.tax_countries contact_country
    on contact_country.id = contact.country_id
   and (
      contact.area = 'regional'
      or (
        contact_country.is_regional = true
        and contact.area = due.category
      )
      or (
        contact.country_id = due.country_id
        and contact.area = due.category
      )
   )
  where
    (
      contact.email_enabled
      and contact.email is not null
      and not exists (
        select 1
        from public.tax_notification_log log
        where log.obligation_id = due.id
          and log.contact_id = contact.id
          and log.alert_date = p_run_date
          and log.channel = 'email'
          and log.status = 'sent'
      )
    )
    or
    (
      contact.google_chat_enabled
      and contact.email is not null
      and not exists (
        select 1
        from public.tax_notification_log log
        where log.obligation_id = due.id
          and log.contact_id = contact.id
          and log.alert_date = p_run_date
          and log.channel = 'google_chat'
          and log.status = 'sent'
      )
    )
  order by due.due_date, due.country_name, contact.full_name;
$$;

revoke all on function public.tax_due_reminders(date) from public, anon, authenticated;
grant execute on function public.tax_due_reminders(date) to service_role;

commit;

-- Verificación opcional:
-- select full_name, email_enabled, google_chat_enabled, calendar_enabled, whatsapp_enabled
-- from public.tax_contacts where active = true order by full_name;
