-- +goose Up
-- +goose StatementBegin

-- =========================================
-- ФУНКЦИЯ: Автоматический аудит действий модератора
-- =========================================
CREATE OR REPLACE FUNCTION audit_moderation_action()
RETURNS TRIGGER AS $$
BEGIN
    -- Проверяем, изменились ли поля модерации
    IF (OLD.moderated_by IS DISTINCT FROM NEW.moderated_by) OR
       (OLD.moderated_at IS DISTINCT FROM NEW.moderated_at) THEN

        -- Определяем тип действия на основе статуса
        IF NEW.status = 'approved' AND OLD.status = 'pending_moderation' THEN
            INSERT INTO moderator_actions (
                moderator_id,
                action_type,
                target_request_id,
                comment,
                metadata
            ) VALUES (
                NEW.moderated_by,
                'approve_request',
                NEW.id,
                NEW.moderation_comment,
                jsonb_build_object(
                    'previous_status', OLD.status::text,
                    'new_status', NEW.status::text,
                    'request_title', NEW.title,
                    'requester_id', NEW.requester_id
                )
            );
        ELSIF NEW.status = 'rejected' AND OLD.status = 'pending_moderation' THEN
            INSERT INTO moderator_actions (
                moderator_id,
                action_type,
                target_request_id,
                comment,
                metadata
            ) VALUES (
                NEW.moderated_by,
                'reject_request',
                NEW.id,
                NEW.moderation_comment,
                jsonb_build_object(
                    'previous_status', OLD.status::text,
                    'new_status', NEW.status::text,
                    'request_title', NEW.title,
                    'requester_id', NEW.requester_id,
                    'rejection_reason', NEW.moderation_comment
                )
            );
        END IF;
    END IF;

    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

COMMENT ON FUNCTION audit_moderation_action() IS 'Автоматически создает записи в moderator_actions при модерации заявок';

-- =========================================
-- ТРИГГЕР: Аудит модерации заявок
-- =========================================
CREATE TRIGGER trigger_audit_request_moderation
    AFTER UPDATE ON requests
    FOR EACH ROW
    WHEN (OLD.moderated_by IS DISTINCT FROM NEW.moderated_by OR
          OLD.moderated_at IS DISTINCT FROM NEW.moderated_at)
    EXECUTE FUNCTION audit_moderation_action();

COMMENT ON TRIGGER trigger_audit_request_moderation ON requests IS
    'Автоматически логирует действия модератора в таблицу moderator_actions';

-- +goose StatementEnd

-- +goose Down
-- +goose StatementBegin
DROP TRIGGER IF EXISTS trigger_audit_request_moderation ON requests;
DROP FUNCTION IF EXISTS audit_moderation_action();
-- +goose StatementEnd
