CREATE TABLE "audit"."medipost_dispatch" (
    "id" bigint generated by default as identity not null,
    "medusa_order_id" text not null,
    "is_medipost_error" boolean not null,
    "is_success" boolean not null,
    "error_message" text,
    "created_at" timestamp with time zone not null default now(),
    "changed_by" uuid default auth.uid()
);

grant usage on schema audit to authenticated;
grant select, insert, update, delete on table audit.medipost_dispatch to authenticated;
grant usage on schema medreport to service_role;

alter table "audit"."medipost_dispatch" enable row level security;

create policy "service_role_select" on "audit"."medipost_dispatch" for select to service_role using (true);
create policy "service_role_insert" on "audit"."medipost_dispatch" for insert to service_role with check (true);
create policy "service_role_update" on "audit"."medipost_dispatch" for update to service_role using (true);
create policy "service_role_delete" on "audit"."medipost_dispatch" for delete to service_role using (true);

CREATE OR REPLACE FUNCTION medreport.get_medipost_dispatch_tries(p_medusa_order_id text)
returns integer
language plpgsql
security definer
as $function$
declare
  tries integer;
begin
  select count(*) from audit.medipost_dispatch m where m.medusa_order_id = p_medusa_order_id and m.created_at > now() - interval '1 day' and m.is_success = false into tries;
  return tries;
end;
$function$;

grant execute on function medreport.get_medipost_dispatch_tries(text) to service_role;
grant select, insert, update, delete on table audit.medipost_dispatch to service_role;
