-- 10-mietvertrag-workflow.sql
-- Document templates bucket, mietvertrag setting, and qualification webhook trigger.

-- 1. Storage bucket for admin-uploaded document templates (private, admin-only)
insert into storage.buckets (id, name, public, file_size_limit, allowed_mime_types)
values (
    'document-templates',
    'document-templates',
    false,
    20971520,
    array['application/vnd.openxmlformats-officedocument.wordprocessingml.document']
)
on conflict (id) do nothing;

-- RLS: only authenticated (admin) can read/write document-templates
drop policy if exists "templates_admin_select" on storage.objects;
create policy "templates_admin_select"
    on storage.objects for select to authenticated
    using (bucket_id = 'document-templates');

drop policy if exists "templates_admin_insert" on storage.objects;
create policy "templates_admin_insert"
    on storage.objects for insert to authenticated
    with check (bucket_id = 'document-templates');

drop policy if exists "templates_admin_update" on storage.objects;
create policy "templates_admin_update"
    on storage.objects for update to authenticated
    using (bucket_id = 'document-templates');

-- 2. Site setting for Mietvertrag template (empty on startup)
insert into public.site_settings (key, value)
values ('mietvertrag_template_path', '')
on conflict (key) do nothing;

-- 3. Function to notify n8n when a lead is qualified (new sales order created)
--    n8n listens on the 'lead_qualified' channel via Postgres trigger.
create or replace function public.notify_lead_qualified()
returns trigger
language plpgsql
security definer
as $$
begin
    perform pg_notify('lead_qualified', json_build_object(
        'sales_order_id', NEW.id,
        'customer_id', NEW.customer_id,
        'lead_id', NEW.lead_id,
        'order_number', NEW.order_number,
        'total_eur', NEW.total_eur,
        'deposit_eur', NEW.deposit_eur,
        'date_from', NEW.date_from,
        'date_to', NEW.date_to,
        'vehicle_label', NEW.vehicle_label
    )::text);
    return NEW;
end;
$$;

-- Trigger on sales_orders insert (fires when qualify_lead creates the order)
drop trigger if exists trg_notify_lead_qualified on public.sales_orders;
create trigger trg_notify_lead_qualified
    after insert on public.sales_orders
    for each row
    execute function public.notify_lead_qualified();

notify pgrst, 'reload schema';
