
create type audit.doctor_page_view_action as ENUM('VIEW_ANALYSIS_RESULTS','VIEW_DASHBOARD','VIEW_OPEN_JOBS','VIEW_OWN_JOBS','VIEW_DONE_JOBS');

create table audit.doctor_page_views (
    "id" bigint generated by default as identity not null,
    "viewer_user_id" uuid references auth.users (id) not null,
    "data_owner_user_id" uuid references auth.users (id),
    "viewed_record_key" text,
    "action" audit.doctor_page_view_action not null,
    "created_at" timestamp with time zone not null default now()
);

grant usage on schema audit to authenticated;
grant select, insert, update, delete on table audit.doctor_page_views to authenticated;

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

create policy "insert_own"
on audit.doctor_page_views
as permissive
for insert
to authenticated
with check (auth.uid() = viewer_user_id);

CREATE OR REPLACE FUNCTION medreport.log_doctor_analysis_feedback_changes()
RETURNS TRIGGER AS $$
DECLARE
    current_user_id uuid;
    current_user_role text;
    operation_type text;
BEGIN
  begin
    current_user_id := auth.uid();
    current_user_role := auth.jwt() ->> 'role';
  end;
    IF (OLD.doctor_user_id IS DISTINCT FROM NEW.doctor_user_id) THEN
        operation_type := CASE 
            WHEN NEW.doctor_user_id IS NULL THEN 'UNSELECT_JOB'
            ELSE 'SELECT_JOB'
        END;
    ELSIF (NEW.status = 'DRAFT' OR (OLD.status IS DISTINCT FROM NEW.status AND NEW.status = 'COMPLETED')) THEN
        operation_type := CASE 
            WHEN NEW.status = 'DRAFT' THEN 'UPDATED_DRAFT'
            WHEN NEW.status = 'COMPLETED' THEN 'PUBLISHED_SUMMARY'
            ELSE NULL
        END;
    ELSE
        operation_type := NULL;
    END IF;
    
    IF operation_type IS NOT NULL THEN
        INSERT INTO audit.log_entries (
            schema_name,
            table_name,
            record_key,
            operation,
            changed_by,
            changed_by_role,
            changed_at
        )
        VALUES (
            'medreport',
            'doctor_analysis_feedback',
            NEW.id::text,
            operation_type,
            current_user_id,
            current_user_role,
            NOW()
        );
    END IF;
    
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS doctor_analysis_feedback_audit_trigger ON medreport.doctor_analysis_feedback;

CREATE TRIGGER doctor_analysis_feedback_audit_trigger
    AFTER UPDATE ON medreport.doctor_analysis_feedback
    FOR EACH ROW
    EXECUTE FUNCTION medreport.log_doctor_analysis_feedback_changes();

GRANT EXECUTE ON FUNCTION medreport.log_doctor_analysis_feedback_changes() TO authenticated;

alter table audit.doctor_page_views enable row level security;
