alter table "public"."audit" drop constraint "audit_pkey";

drop index if exists "public"."audit_pkey";

drop table "public"."audit";

set check_function_bodies = off;

CREATE OR REPLACE FUNCTION public.do_usr_audit()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$
  declare
    audit_kind public.audit_kind;
    usr_id int;
    prev_username public.usr_username := null;
    prev_password public.hashed_text   := null;
    prev_email    public.email         := null;
  begin
    if (TG_OP = 'UPDATE') then
      usr_id := OLD.id;
      audit_kind := 'modify';
      prev_username := OLD.username;
      prev_password := OLD.password;
      prev_email := OLD.email;
    elsif (TG_OP = 'INSERT') then
      usr_id := NEW.id;
      audit_kind := 'create';
    end if;

    insert into public.usr_audit
      (kind, usr, actor, prev_username, prev_email, prev_password )
    values
      -- TODO actor
      (audit_kind, usr_id, usr_id, prev_username, prev_email, prev_password );

    return NEW;
  end;
$function$
;

CREATE OR REPLACE FUNCTION public.do_usr_soft_delete()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$
  declare
    audit_id int;
  begin
    insert into public.usr_audit
      (kind, usr, actor)
    values
      -- TODO actor
      ('delete' :: public.audit_kind, OLD.id, OLD.id);

    update public.usr
    set deleted = true
    where id = OLD.id;

    return null;
  end;
$function$
;


