--
-- workflow_case__delete/1
--
create or replace function workflow_case__delete(
  integer
) returns int4 as $$

declare
  delete__case_id                alias for $1;  
  v_workflow_case_table          varchar;   
begin
        /* delete attribute_value_audit, tokens, tasks  */
        delete from wf_attribute_value_audit 
         where case_id = delete__case_id;

        delete from wf_case_assignments 
         where case_id = delete__case_id;

        delete from wf_case_deadlines 
         where case_id = delete__case_id;

        delete from wf_tokens 
         where case_id = delete__case_id;

        delete from wf_task_assignments 
         where task_id in (select task_id 
                             from wf_tasks 
                            where case_id = delete__case_id);

        delete from wf_tasks 
         where case_id = delete__case_id;

        /* delete the journal */
        PERFORM journal_entry__delete_for_object(delete__case_id);
        
        /* delete from the workflow-specific cases table */
        select table_name into v_workflow_case_table
        from   acs_object_types ot, wf_cases c
        where  c.case_id = delete__case_id
        and    object_type = c.workflow_key;
        
        execute 'delete from ' || v_workflow_case_table || ' where case_id = ' || delete__case_id;

        /* delete from the generic cases table */
        delete from wf_cases where case_id = delete__case_id;

        /* delete from acs-objects */
        PERFORM acs_object__delete(delete__case_id);

        return 0; 
end;$$ language plpgsql;