-- Seguimiento de Impuestos GLM
-- Actualización final: contactos regionales de Nómina y enrutamiento global por categoría.
-- Ejecutar una sola vez en Supabase SQL Editor sobre la base ya instalada.

begin;

-- Los contactos ubicados en el país Regional pueden especializarse por categoría:
-- area = regional  -> recibe todas las obligaciones
-- area = nomina    -> recibe Nómina de todos los países
-- area = admin     -> recibe Administración de todos los países
create or replace 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,
  contact_whatsapp text,
  email_enabled boolean,
  whatsapp_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.whatsapp_number as contact_whatsapp,
    (
      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.whatsapp_enabled
      and contact.whatsapp_number 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 = 'whatsapp'
          and log.status = 'sent'
      )
    ) as whatsapp_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.whatsapp_enabled
      and contact.whatsapp_number 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 = 'whatsapp'
          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;

-- Actualiza los contactos si ya existen.
with regional_country as (
  select id
  from public.tax_countries
  where code = 'REG'
  limit 1
),
contact_data(full_name, email, whatsapp_number, job_title) as (
  values
    ('Mati Soto Valenzuela', 'msoto@gomezleemarketing.com', '18094037571', 'Nómina Regional'),
    ('Iveth Herrera', 'iherrera@gomezleemarketing.com', '50376373732', 'Nómina Regional')
)
update public.tax_contacts contact
set country_id = regional_country.id,
    full_name = data.full_name,
    whatsapp_number = data.whatsapp_number,
    job_title = data.job_title,
    area = 'nomina',
    email_enabled = true,
    whatsapp_enabled = true,
    active = true,
    updated_at = now()
from contact_data data
cross join regional_country
where lower(contact.email) = lower(data.email);

-- Inserta los contactos que todavía no existen.
with regional_country as (
  select id
  from public.tax_countries
  where code = 'REG'
  limit 1
),
contact_data(full_name, email, whatsapp_number, job_title) as (
  values
    ('Mati Soto Valenzuela', 'msoto@gomezleemarketing.com', '18094037571', 'Nómina Regional'),
    ('Iveth Herrera', 'iherrera@gomezleemarketing.com', '50376373732', 'Nómina Regional')
)
insert into public.tax_contacts (
  country_id,
  full_name,
  email,
  whatsapp_number,
  job_title,
  area,
  email_enabled,
  whatsapp_enabled,
  active
)
select
  regional_country.id,
  data.full_name,
  lower(data.email),
  data.whatsapp_number,
  data.job_title,
  'nomina',
  true,
  true,
  true
from contact_data data
cross join regional_country
where not exists (
  select 1
  from public.tax_contacts existing
  where lower(existing.email) = lower(data.email)
);

commit;
