-- ============================================================
--  Magic Tech — ربط نظام المبيعات (طلبات واردة)
--  شغّل هذا الملف مرّة واحدة في:  Supabase → SQL Editor → New query → Run
--  بعد التشغيل: غيّر السر في الدالة (CHANGE_ME_SECRET_123) لسر قوي.
-- ============================================================

-- ---------- 1) جدول رؤوس الطلبات/الفواتير الواردة ----------
create table if not exists public.sales_orders (
  id            bigint generated always as identity primary key,
  source        text        not null default 'sales',   -- مصدر الطلب (نظام المبيعات)
  external_id   text,                                    -- رقم الفاتورة في نظام المبيعات (لمنع التكرار)
  invoice_no    text,                                    -- رقم الفاتورة الظاهر
  invoice_date  timestamptz,                             -- تاريخ الفاتورة
  customer_name text,
  seller_name   text,
  note          text,
  status        text        not null default 'pending',  -- pending | accepted | rejected
  total_amount  numeric,                                 -- قيمة الفاتورة (اختياري)
  raw           jsonb,                                   -- نسخة خام من البيانات المُرسلة (أرشفة)
  created_at    timestamptz not null default now(),
  accepted_by   uuid,                                    -- مين قبِل الطلب (profiles.id)
  accepted_at   timestamptz,
  unique (source, external_id)                           -- منع تكرار نفس الفاتورة
);

-- ---------- 2) جدول بنود الطلب ----------
create table if not exists public.sales_order_items (
  id            bigint generated always as identity primary key,
  order_id      bigint  not null references public.sales_orders(id) on delete cascade,
  line_no       int,
  barcode       text,
  model         text,
  description   text,
  qty           numeric not null default 0,
  unit_price    numeric,
  -- حقول التجهيز (تُملأ وقت القبول من صفحة المستودع)
  item_id       text,                                    -- بعد المطابقة مع جدول items
  warehouse     text,                                    -- المستودع الذي خُصم منه
  fulfilled_qty numeric not null default 0,
  match_status  text    not null default 'unmatched',    -- matched | unmatched
  note          text
);

create index if not exists idx_sales_orders_status      on public.sales_orders(status);
create index if not exists idx_sales_order_items_order   on public.sales_order_items(order_id);

-- ---------- 3) الحماية (RLS) ----------
alter table public.sales_orders      enable row level security;
alter table public.sales_order_items enable row level security;

-- موظفو المستودع (مسجّلو الدخول) يقرأون ويعدّلون
drop policy if exists "auth_read_orders"        on public.sales_orders;
drop policy if exists "auth_update_orders"      on public.sales_orders;
drop policy if exists "auth_read_order_items"   on public.sales_order_items;
drop policy if exists "auth_update_order_items" on public.sales_order_items;

create policy "auth_read_orders"        on public.sales_orders
  for select to authenticated using (true);
create policy "auth_update_orders"      on public.sales_orders
  for update to authenticated using (true) with check (true);

create policy "auth_read_order_items"   on public.sales_order_items
  for select to authenticated using (true);
create policy "auth_update_order_items" on public.sales_order_items
  for update to authenticated using (true) with check (true);
-- ملاحظة: لا يوجد سماح INSERT للعموم — الإدخال يتم فقط عبر الدالة أدناه (security definer)

-- ---------- 4) دالة الاستقبال (نقطة الـ API لنظام المبيعات) ----------
create or replace function public.ingest_sales_order(payload jsonb)
returns jsonb
language plpgsql
security definer
set search_path = public
as $$
declare
  v_secret   text   := 'CHANGE_ME_SECRET_123';   -- 🔴 غيّره لسر قوي (نفسه يُعطى للمبرمج)
  v_token    text   := payload->>'token';
  v_source   text   := coalesce(payload->>'source','sales');
  v_ext      text   := nullif(payload->>'external_id','');
  v_order_id bigint;
  v_item     jsonb;
  v_ln       int    := 0;
  v_barcode  text;
  v_model    text;
  v_item_id  text;
begin
  -- (1) تحقق السر
  if v_token is distinct from v_secret then
    raise exception 'unauthorized: invalid token';
  end if;

  -- (2) منع التكرار: لو نفس رقم الفاتورة موجود، أرجِع الموجود بدل تكراره
  if v_ext is not null then
    select id into v_order_id
      from sales_orders
     where source = v_source and external_id = v_ext;
    if v_order_id is not null then
      return jsonb_build_object('ok', true, 'duplicate', true, 'order_id', v_order_id);
    end if;
  end if;

  -- (3) أدخِل رأس الطلب
  insert into sales_orders(source, external_id, invoice_no, invoice_date,
                           customer_name, seller_name, note, total_amount, raw)
  values (
    v_source,
    v_ext,
    payload->>'invoice_no',
    nullif(payload->>'invoice_date','')::timestamptz,
    payload->>'customer_name',
    payload->>'seller_name',
    payload->>'note',
    nullif(payload->>'total_amount','')::numeric,
    payload
  )
  returning id into v_order_id;

  -- (4) أدخِل البنود + حاول المطابقة مع جدول items (بالباركود أولاً ثم الموديل)
  for v_item in
    select value from jsonb_array_elements(coalesce(payload->'items','[]'::jsonb)) as t(value)
  loop
    v_ln      := v_ln + 1;
    v_barcode := nullif(v_item->>'barcode','');
    v_model   := nullif(v_item->>'model','');
    v_item_id := null;

    select i.item_id::text into v_item_id
      from items i
     where (v_barcode is not null and i.barcode = v_barcode)
        or (v_model   is not null and lower(i.model) = lower(v_model))
     limit 1;

    insert into sales_order_items(order_id, line_no, barcode, model, description,
                                  qty, unit_price, note, item_id, match_status)
    values (
      v_order_id, v_ln, v_barcode, v_model,
      v_item->>'description',
      coalesce(nullif(v_item->>'qty',''),'0')::numeric,
      nullif(v_item->>'unit_price','')::numeric,
      v_item->>'note',
      v_item_id,
      case when v_item_id is not null then 'matched' else 'unmatched' end
    );
  end loop;

  return jsonb_build_object('ok', true, 'order_id', v_order_id, 'lines', v_ln);
end;
$$;

-- اسمح باستدعاء الدالة (السر داخلها هو الحماية الفعلية)
grant execute on function public.ingest_sales_order(jsonb) to anon, authenticated;

-- ============================================================
--  تم. الخطوة التالية:
--   1) غيّر CHANGE_ME_SECRET_123 لسر قوي (Run مرة ثانية بعد التغيير).
--   2) أعطِ المبرمج ملف: API_نظام_المبيعات.md
-- ============================================================
